[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
} else {
$isIp = (bool) ip2long($pieces['host']);
if ($isIp) {
return $pieces['host'];
}
}
return false;
}
function siteMap() {
_error_log("siteMap: start");
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
global $global, $advancedCustom;
$date = date('Y-m-d\TH:i:s') . "+00:00";
$xml = '
' . $global['webSiteRootURL'] . '
' . $date . '
always
1.00
' . $global['webSiteRootURL'] . 'help
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'about
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'contact
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'channels
' . $date . '
daily
0.80
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
_error_log("siteMap: rowCount {$_REQUEST['rowCount']} ");
$_POST['sort']['modified'] = "DESC";
$users = User::getAllUsersThatHasVideos(true);
_error_log("siteMap: getAllUsers " . count($users));
foreach ($users as $value) {
$xml .= '
' . User::getChannelLink($value['id']) . '
' . $date . '
daily
0.90
';
}
$xml .= '
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
$_POST['sort']['modified'] = "DESC";
$rows = Category::getAllCategories();
_error_log("siteMap: getAllCategories " . count($rows));
foreach ($rows as $value) {
$xml .= '
' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . '
' . $date . '
weekly
0.80
';
}
$xml .= '';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10;
$_POST['sort']['created'] = "DESC";
$rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly");
_error_log("siteMap: getAllVideos " . count($rows));
foreach ($rows as $video) {
$videos_id = $video['id'];
//_error_log("siteMap: getAllVideos videos_id {$videos_id} start");
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = parseDurationToSeconds($video['duration']);
if ($duration > 28800) {
// this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore
$duration = 28800;
}
$xml .= '
' . Video::getLink($video['id'], $video['clean_title']) . '
' . $img . '
' . $duration . '
' . $video['views_count'] . '
' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00
yes
' . (Video::isPublic($video['id']) ? "no" : "yes") . '
' . User::getNameIdentificationById($video['users_id']) . '
no
';
}
$xml .= ' ';
_error_log("siteMap: done ");
$newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml);
if (empty($newXML1)) {
_error_log("siteMap: pregreplace1 fail ");
$newXML1 = $xml;
}
if (!empty($advancedCustom->siteMapUTF8Fix)) {
$newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1);
if (empty($newXML2)) {
_error_log("siteMap: pregreplace2 fail ");
$newXML2 = $newXML1;
}
$newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2);
if (empty($newXML3)) {
_error_log("siteMap: pregreplace3 fail ");
$newXML3 = $newXML2;
}
$newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3);
if (empty($newXML4)) {
_error_log("siteMap: pregreplace4 fail ");
$newXML4 = $newXML3;
}
$newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4);
if (empty($newXML5)) {
_error_log("siteMap: pregreplace5 fail ");
$newXML5 = $newXML4;
}
} else {
$newXML5 = $newXML1;
}
return $newXML5;
}
function object_to_array($obj) {
//only process if it's an object or array being passed to the function
if (is_object($obj) || is_array($obj)) {
$ret = (array) $obj;
foreach ($ret as &$item) {
//recursively process EACH element regardless of type
$item = object_to_array($item);
}
return $ret;
}
//otherwise (i.e. for scalar values) return without modification
else {
return $obj;
}
}
function allowOrigin() {
global $global;
if (empty($_SERVER['HTTP_ORIGIN'])) {
$server = parse_url($global['webSiteRootURL']);
header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com');
} else {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
}
function rrmdir($dir) {
global $global;
if ($dir == getVideosDir() . "" || $dir == "{$global['systemRootPath']}videos") {
return false;
}
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir . "/" . $object)) {
rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
rmdir($dir);
}
}
/**
* You can now configure it on the configuration.php
* @return boolean
*/
function ddosProtection() {
global $global;
$maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections'];
$secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout'];
$whitelistedFiles = array(
'playlists.json.php',
'playlistsFromUserVideos.json.php',
'image404.php'
);
if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) {
return true;
}
$time = time();
if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) {
$_SESSION['bruteForceBlock'] = array();
$_SESSION['bruteForceBlock'][] = $time;
return true;
}
$_SESSION['bruteForceBlock'][] = $time;
//remove requests that are older than secondTimeout
foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) {
if ($request_time < $time - $secondTimeout) {
unset($_SESSION['bruteForceBlock'][$key]);
}
}
//progressive timeout-> more requests, longer timeout
$active_connections = count($_SESSION['bruteForceBlock']);
$timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout;
if ($timeoutReal) {
_error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY);
}
sleep($timeoutReal);
//with strict mode, penalize "attacker" with sleep() above, log and then die
if ($global['strictDDOSprotection'] && $timeoutReal > 0) {
$str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']);
_error_log($str);
die($str);
}
return true;
}
function getAdsLeaderBoardBigVideo() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value);
}
}
}
function getAdsLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop->value);
}
}
}
function getAdsChannelLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value);
}
}
}
function getAdsLeaderBoardTop2() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value);
}
}
}
function getAdsLeaderBoardMiddle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value);
}
}
}
function getAdsLeaderBoardFooter() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value);
}
}
}
function getAdsSideRectangle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
} else {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
}
}
}
function isToHidePrivateVideos() {
$obj = AVideoPlugin::getObjectDataIfEnabled("Gallery");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouTube");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
return false;
}
function convertImageToOG($source, $destination) {
if (!file_exists($destination)) {
$w = 200;
$h = 200;
$sizes = getimagesize($source);
if ($sizes[0] < $w || $sizes[1] < $h) {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
unlink($fileConverted);
}
}
return $destination;
}
function convertImageToRoku($source, $destination) {
if (empty($source)) {
_error_log("convertImageToRoku: source image is empty");
return false;
}
$w = 1280;
$h = 720;
if (file_exists($destination)) {
$sizes = getimagesize($destination);
if ($sizes[0] < $w || $sizes[1] < $h) {
_error_log("convertImageToRoku: file is smaller " . json_encode($sizes));
unlink($destination);
}
}
if (!file_exists($destination)) {
try {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
@unlink($fileConverted);
} catch (Exception $exc) {
_error_log("convertImageToRoku: " . $exc->getMessage());
return false;
}
}
return $destination;
}
function ogSite() {
global $global, $config;
include $global['systemRootPath'] . 'objects/functionogSite.php';
}
function getOpenGraph($videos_id) {
global $global, $config, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php';
}
function getLdJson($videos_id) {
$cache = ObjectYPT::getCache("getLdJson{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getLdJson{$videos_id}", $output);
echo $output;
}
function getItemprop($videos_id) {
$cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'image') {
$type = 'image';
}
if ($video['type'] === 'zip') {
$type = 'zip';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getItemprop{$videos_id}", $output);
echo $output;
}
function getOS($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
function get_browser_name($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
if (empty($user_agent)) {
return 'Unknow';
}
// Make case insensitive.
$t = strtolower($user_agent);
// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
// "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
// http://php.net/manual/en/function.strpos.php
$t = " " . $t;
// Humans / Regular Users
if (isAVideoStreamer($t)) {
return 'AVideo Mobile App';
} elseif ($url = isAVideoEncoder($t)) {
return 'AVideo Encoder ' . $url;
} elseif ($url = isAVideoStreamer($t)) {
return 'AVideo Streamer ' . $url;
} elseif (strpos($t, 'crkey')) {
return 'Chromecast';
} elseif (strpos($t, 'opera') || strpos($t, 'opr/')) {
return 'Opera';
} elseif (strpos($t, 'edge')) {
return 'Edge';
} elseif (strpos($t, 'chrome')) {
return 'Chrome';
} elseif (strpos($t, 'safari')) {
return 'Safari';
} elseif (strpos($t, 'firefox')) {
return 'Firefox';
} elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) {
return 'Internet Explorer';
} elseif (strpos($t, 'applecoremedia')) {
return 'Native Apple Player';
}
// Search Engines
elseif (strpos($t, 'google')) {
return '[Bot] Googlebot';
} elseif (strpos($t, 'bing')) {
return '[Bot] Bingbot';
} elseif (strpos($t, 'slurp')) {
return '[Bot] Yahoo! Slurp';
} elseif (strpos($t, 'duckduckgo')) {
return '[Bot] DuckDuckBot';
} elseif (strpos($t, 'baidu')) {
return '[Bot] Baidu';
} elseif (strpos($t, 'yandex')) {
return '[Bot] Yandex';
} elseif (strpos($t, 'sogou')) {
return '[Bot] Sogou';
} elseif (strpos($t, 'exabot')) {
return '[Bot] Exabot';
} elseif (strpos($t, 'msn')) {
return '[Bot] MSN';
}
// Common Tools and Bots
elseif (strpos($t, 'mj12bot')) {
return '[Bot] Majestic';
} elseif (strpos($t, 'ahrefs')) {
return '[Bot] Ahrefs';
} elseif (strpos($t, 'semrush')) {
return '[Bot] SEMRush';
} elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) {
return '[Bot] Moz or OpenSiteExplorer';
} elseif (strpos($t, 'frog') || strpos($t, 'screaming')) {
return '[Bot] Screaming Frog';
}
// Miscellaneous
elseif (strpos($t, 'facebook')) {
return '[Bot] Facebook';
} elseif (strpos($t, 'pinterest')) {
return '[Bot] Pinterest';
}
// Check for strings commonly used in bot user agents
elseif (strpos($t, 'crawler') || strpos($t, 'api') ||
strpos($t, 'spider') || strpos($t, 'http') ||
strpos($t, 'bot') || strpos($t, 'archive') ||
strpos($t, 'info') || strpos($t, 'data')) {
return '[Bot] Other';
}
//_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI());
return 'Other (Unknown)';
}
/**
* Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7
* we need to detect the chrome browser and load an older version
*
*/
function isOldChromeVersion() {
$global;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
if (!empty($global['forceOldChrome'])) {
return true;
}
if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
return version_compare($matches[1], '80', '<=');
}
return false;
}
function TimeLogStart($name) {
global $global;
if (!empty($global['noDebug'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
if (empty($global['start']) || !is_array($global['start'])) {
$global['start'] = array();
}
$global['start'][$name] = $time;
}
function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) {
global $global;
if (!empty($global['noDebug'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $global['start'][$name]), 4);
if ($total_time > $TimeLogLimit) {
_error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}");
}
TimeLogStart($name);
}
class AVideoLog {
public static $DEBUG = 0;
public static $WARNING = 1;
public static $ERROR = 2;
public static $SECURITY = 3;
+ public static $SOCKET = 4;
}
function _error_log($message, $type = 0, $doNotRepeat = false) {
if (empty($doNotRepeat)) {
// do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error
$doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']);
}
if ($doNotRepeat) {
return false;
}
global $global;
if (!empty($global['noDebug']) && $type == 0) {
return false;
}
- if(!is_string($message)){
+ if (!is_string($message)) {
$message = json_encode($message);
}
$prefix = "AVideoLog::";
switch ($type) {
case AVideoLog::$DEBUG:
$prefix .= "DEBUG: ";
break;
case AVideoLog::$WARNING:
$prefix .= "WARNING: ";
break;
case AVideoLog::$ERROR:
$prefix .= "ERROR: ";
break;
case AVideoLog::$SECURITY:
$prefix .= "SECURITY: ";
break;
+ case AVideoLog::$SOCKET:
+ $prefix .= "SOCKET: ";
+ break;
}
error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}");
}
function postVariables($url, $array) {
if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) {
return false;
}
$array = object_to_array($array);
$ch = curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// execute!
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// close the connection, release resources used
curl_close($ch);
if ($httpcode == 200) {
return true;
}
return $httpcode;
}
function _session_start(array $options = array()) {
try {
if (session_status() == PHP_SESSION_NONE) {
return @session_start($options);
}
} catch (Exception $exc) {
_error_log("_session_start: " . $exc->getTraceAsString());
return false;
}
}
function _mysql_connect() {
global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort;
if (is_object($global['mysqli']) && empty(@$global['mysqli']->ping())) {
try {
$global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort);
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
} catch (Exception $exc) {
_error_log($exc->getTraceAsString());
return false;
}
}
}
function _mysql_close() {
global $global;
if (is_object($global['mysqli']) && !empty(@$global['mysqli']->ping())) {
@$global['mysqli']->close();
}
}
function remove_utf8_bom($text) {
if (strlen($text) > 1000000) {
return $text;
}
$bom = pack('H*', 'EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
function getCacheDir() {
$p = AVideoPlugin::loadPlugin("Cache");
return $p->getCacheDir();
}
function clearCache() {
global $global;
$dir = getVideosDir() . "cache/";
if (!empty($_GET['FirstPage'])) {
$dir .= "firstPage/";
}
rrmdir($dir);
$dir = getCacheDir();
if (!empty($_GET['FirstPage'])) {
$dir .= "firstPage/";
}
rrmdir($dir);
ObjectYPT::deleteCache("getEncoderURL");
}
function getUsageFromFilename($filename, $dir = "") {
global $global;
if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
if (empty($dir)) {
$dir = getVideosDir() . "";
}
$pos = strrpos($dir, '/');
$dir .= (($pos === false) ? "/" : "");
$totalSize = 0;
_error_log("getUsageFromFilename: start {$dir}{$filename}");
//$files = glob("{$dir}{$filename}*");
$files = globVideosDir($filename);
session_write_close();
$filesProcessed = array();
if (empty($files)) {
_error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one");
file_put_contents("{$dir}{$filename}.notfound", time());
$totalSize = 10;
} else {
foreach ($files as $f) {
if (strpos($f, '.size.lock') !== false) {
continue;
}
if (is_dir($f)) {
_error_log("getUsageFromFilename: {$f} is Dir");
$dirSize = getDirSize($f);
$totalSize += $dirSize;
if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) {
// probably the HLS file is hosted on the YPTStorage
$info = YPTStorage::getFileInfo($filename);
if (!empty($info->size)) {
$totalSize += $info->size;
}
}
} elseif (is_file($f)) {
$filesize = filesize($f);
if ($filesize < 20) { // that means it is a dummy file
$lockFile = $f . ".size.lock";
if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) {
file_put_contents($lockFile, time());
_error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})");
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
//$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
if (!empty($aws_s3)) {
_error_log("getUsageFromFilename: Get from S3");
$filesize += $aws_s3->getFilesize($filename);
} elseif (!empty($bb_b2)) {
// TODO
} else {
$urls = Video::getVideosPaths($filename, true);
_error_log("getUsageFromFilename: Paths " . json_encode($urls));
if (!empty($urls["m3u8"]['url'])) {
$filesize += getUsageFromURL($urls["m3u8"]['url']);
}
if (!empty($urls['mp4'])) {
foreach ($urls['mp4'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls['webm'])) {
foreach ($urls['webm'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls["pdf"]['url'])) {
$filesize += getUsageFromURL($urls["pdf"]['url']);
}
if (!empty($urls["image"]['url'])) {
$filesize += getUsageFromURL($urls["image"]['url']);
}
if (!empty($urls["zip"]['url'])) {
$filesize += getUsageFromURL($urls["zip"]['url']);
}
if (!empty($urls["mp3"]['url'])) {
$filesize += getUsageFromURL($urls["mp3"]['url']);
}
}
unlink($lockFile);
}
} else {
_error_log("getUsageFromFilename: {$f} is File ({$filesize})");
}
$totalSize += $filesize;
}
}
}
return $totalSize;
}
/**
* Returns the size of a file without downloading it, or -1 if the file
* size could not be determined.
*
* @param $url - The location of the remote file to download. Cannot
* be null or empty.
*
* @return The size of the file referenced by $url, or false if the size
* could not be determined.
*/
function getUsageFromURL($url) {
global $global;
if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
_error_log("getUsageFromURL: start ({$url})");
// Assume failure.
$result = false;
$curl = curl_init($url);
_error_log("getUsageFromURL: curl_init ");
try {
// Issue a HEAD request and follow any redirects.
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string());
$data = curl_exec($curl);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
_error_log("getUsageFromURL: ERROR " . $exc->getMessage());
_error_log("getUsageFromURL: ERROR " . curl_errno($curl));
_error_log("getUsageFromURL: ERROR " . curl_error($curl));
}
if ($data) {
_error_log("getUsageFromURL: response header " . $data);
$content_length = "unknown";
$status = "unknown";
if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) {
$status = (int) $matches[1];
}
if (preg_match("/Content-Length: (\d+)/", $data, $matches)) {
$content_length = (int) $matches[1];
}
// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if ($status == 200 || ($status > 300 && $status <= 308)) {
$result = $content_length;
}
} else {
_error_log("getUsageFromURL: ERROR no response data " . curl_error($curl));
}
curl_close($curl);
return (int) $result;
}
function getDirSize($dir) {
_error_log("getDirSize: start {$dir}");
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return foldersize($dir);
} else {
$command = "du -sb {$dir}";
exec($command . " < /dev/null 2>&1", $output, $return_val);
if ($return_val !== 0) {
_error_log("getDirSize: ERROR ON Command {$command}");
return 0;
} else {
if (!empty($output[0])) {
preg_match("/^([0-9]+).*/", $output[0], $matches);
}
if (!empty($matches[1])) {
_error_log("getDirSize: found {$matches[1]} from - {$output[0]}");
return intval($matches[1]);
}
_error_log("getDirSize: ERROR on pregmatch {$output[0]}");
return 0;
}
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/') . '/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function getDiskUsage() {
global $global;
$dir = getVideosDir() . "";
$obj = new stdClass();
$obj->disk_free_space = disk_free_space($dir);
$obj->disk_total_space = disk_total_space($dir);
$obj->videos_dir = getDirSize($dir);
$obj->disk_used = $obj->disk_total_space - $obj->disk_free_space;
$obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir;
$obj->disk_free_space_human = humanFileSize($obj->disk_free_space);
$obj->disk_total_space_human = humanFileSize($obj->disk_total_space);
$obj->videos_dir_human = humanFileSize($obj->videos_dir);
$obj->disk_used_human = humanFileSize($obj->disk_used);
$obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other);
// percentage of disk used
$obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100);
$obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100);
$obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100);
return $obj;
}
function unsetSearch() {
unset($_GET['searchPhrase']);
unset($_POST['searchPhrase']);
unset($_GET['search']);
unset($_GET['q']);
}
function encrypt_decrypt($string, $action) {
global $global;
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = $global['systemRootPath'];
while (strlen($secret_iv) < 16) {
$secret_iv .= $global['systemRootPath'];
}
// hash
$key = hash('sha256', $global['salt']);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} elseif ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
function compressString($string) {
if (function_exists("gzdeflate")) {
$string = gzdeflate($string, 9);
}
return $string;
}
function decompressString($string) {
if (function_exists("gzinflate")) {
$string = gzinflate($string);
}
return $string;
}
function encryptString($string) {
if (is_object($string)) {
$string = json_encode($string);
}
return encrypt_decrypt($string, 'encrypt');
}
function decryptString($string) {
return encrypt_decrypt($string, 'decrypt');
}
function getToken($timeout = 0, $salt = "") {
global $global;
$obj = new stdClass();
$obj->salt = $global['salt'] . $salt;
if (!empty($timeout)) {
$obj->time = time();
$obj->timeout = $obj->time + $timeout;
} else {
$obj->time = strtotime("Today 00:00:00");
$obj->timeout = strtotime("Today 23:59:59");
$obj->timeout += cacheExpirationTime();
}
$strObj = json_encode($obj);
//_error_log("Token created: {$strObj}");
return encryptString($strObj);
}
-function isTokenValid($token, $salt = ""){
+function isTokenValid($token, $salt = "") {
return verifyToken($token, $salt);
}
function verifyToken($token, $salt = "") {
global $global;
$obj = json_decode(decryptString($token));
if (empty($obj)) {
_error_log("verifyToken invalid token");
return false;
}
if ($obj->salt !== $global['salt'] . $salt) {
_error_log("verifyToken salt fail");
return false;
}
$time = time();
if (!($time >= $obj->time && $time <= $obj->timeout)) {
_error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout");
return false;
}
return true;
}
class YPTvideoObject {
public $id;
public $title;
public $description;
public $thumbnails;
public $channelTitle;
public $videoLink;
public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) {
$this->id = $id;
$this->title = $title;
$this->description = $description;
$this->thumbnails = $thumbnails;
$this->channelTitle = $channelTitle;
$this->videoLink = $videoLink;
}
}
function isToShowDuration($type) {
$notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks');
if (in_array($type, $notShowTo)) {
return false;
} else {
return true;
}
}
function _dieAndLogObject($obj, $prefix = "") {
$objString = json_encode($obj);
_error_log($prefix . $objString);
die($objString);
}
function isAVideoPlayer() {
if (isVideo()) {
return true;
}
return false;
}
function isVideo() {
global $isModeYouTube;
return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive();
}
function isAudio() {
global $isAudio;
return !empty($isAudio);
}
function isSerie() {
return isPlayList();
}
function isPlayList() {
global $isPlayList, $isSerie;
return !empty($isSerie) || !empty($isPlayList);
}
function isChannel() {
global $isChannel;
if (!empty($isChannel) && !isVideo()) {
$user_id = 0;
if (empty($_GET['channelName'])) {
if (User::isLogged()) {
$user_id = User::getId();
} else {
return false;
}
} else {
$_GET['channelName'] = xss_esc($_GET['channelName']);
$user = User::getChannelOwner($_GET['channelName']);
if (!empty($user)) {
$user_id = $user['id'];
} else {
$user_id = $_GET['channelName'];
}
}
return $user_id;
}
return false;
}
function isEmbed() {
global $isEmbed;
return !empty($isEmbed);
}
function isLive() {
global $isLive;
- return !empty($isLive);
+ if(!empty($isLive)){
+ return getLiveKey();
+ }else{
+ return false;
+ }
+}
+
+function getLiveKey() {
+ global $getLiveKey;
+ if(empty($getLiveKey)){
+ return false;
+ }
+ return $getLiveKey;
+}
+
+function setLiveKey($key, $live_servers_id){
+ global $getLiveKey;
+ $getLiveKey = array('key'=>$key,'live_servers_id'=>intval($live_servers_id));
+ return $getLiveKey;
}
function isVideoPlayerHasProgressBar() {
if (isLive()) {
$obj = AVideoPlugin::getObjectData('Live');
if (empty($obj->disableDVR)) {
return true;
}
} elseif (isAVideoPlayer()) {
return true;
}
return false;
}
function isHLS() {
global $video, $global;
if (isLive()) {
return true;
} elseif (!empty($video) && $video['type'] == 'video' && file_exists(getVideosDir() . "{$video['filename']}/index.m3u8")) {
return true;
}
return false;
}
function getRedirectUri() {
if (!empty($_GET['redirectUri'])) {
return $_GET['redirectUri'];
}
if (!empty($_SERVER["HTTP_REFERER"])) {
return $_SERVER["HTTP_REFERER"];
}
return getRequestURI();
}
function getRequestURI() {
if (empty($_SERVER['REQUEST_URI'])) {
return "";
}
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
function getSelfURI() {
- if (empty($_SERVER['PHP_SELF'])) {
+ if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) {
return "";
}
- $queryStringWithoutError = preg_replace("/error=[^&]*/", "", $_SERVER['QUERY_STRING']);
- $phpselfWithoutIndex = preg_replace("/index.php/", "", $_SERVER['PHP_SELF']);
+ $queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']);
+ $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']);
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError";
$url = rtrim($url, '?');
return $url;
}
function isSameVideoAsSelfURI($url) {
return URLsAreSameVideo($url, getSelfURI());
}
function URLsAreSameVideo($url1, $url2) {
$videos_id1 = getVideoIDFromURL($url1);
$videos_id2 = getVideoIDFromURL($url2);
if (empty($videos_id1) || empty($videos_id2)) {
return false;
}
return $videos_id1 === $videos_id2;
}
+function getVideos_id(){
+ if(isVideo()){
+ return getVideoIDFromURL(getSelfURI());
+ }
+ return false;
+}
+
function getVideoIDFromURL($url) {
if (preg_match("/v=([0-9]+)/", $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
}
function getBackURL() {
global $global;
$backURL = getRedirectUri();
if (empty($backURL)) {
$backURL = getRequestURI();
}
if (isSameVideoAsSelfURI($backURL)) {
$backURL = getHomeURL();
}
return $backURL;
}
function getHomeURL() {
global $global, $advancedCustomUser, $advancedCustom;
if (isValidURL($advancedCustomUser->afterLoginGoToURL)) {
return $advancedCustomUser->afterLoginGoToURL;
} elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) {
return $advancedCustom->logoMenuBarURL;
}
return $global['webSiteRootURL'];
}
function isValidURL($url) {
//var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL));
if (empty($url) || !is_string($url)) {
return false;
}
if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) {
return true;
}
return false;
}
function hasLastSlash($word) {
return substr($word, -1) === '/';
}
function addLastSlash($word) {
return $word . (hasLastSlash($word) ? "" : "/");
}
function URLHasLastSlash() {
return hasLastSlash($_SERVER["REQUEST_URI"]);
}
function ucname($str) {
$str = ucwords(strtolower($str));
foreach (array('\'', '-') as $delim) {
if (strpos($str, $delim) !== false) {
$str = implode($delim, array_map('ucfirst', explode($delim, $str)));
}
}
return $str;
}
function sanitize_input($input) {
return htmlentities(strip_tags($input));
}
function sanitize_array_item(&$item, $key) {
$item = sanitize_input($item);
}
function getSEOComplement($parameters = array()) {
global $config;
$allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null;
$addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true;
$addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true;
$parts = array();
if (!empty($_GET['error'])) {
array_push($parts, __("Error"));
}
if ($addCategory && !empty($_GET['catName'])) {
array_push($parts, $_GET['catName']);
}
if (!empty($_GET['channelName'])) {
array_push($parts, $_GET['channelName']);
}
if (!empty($_GET['type'])) {
$type = $_GET['type'];
if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) {
array_push($parts, __(ucname($type)));
}
}
if (!empty($_GET['showOnly'])) {
array_push($parts, $_GET['showOnly']);
}
if (!empty($_GET['page'])) {
$page = intval($_GET['page']);
if ($page > 1) {
array_push($parts, sprintf(__("Page %d"), $page));
}
}
// Cleaning all entries in the $parts array
array_walk($parts, 'sanitize_array_item');
$txt = implode($config->getPageTitleSeparator(), $parts);
$txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt;
return $txt;
}
function getCurrentPage() {
if (!empty($_REQUEST['current'])) {
return intval($_REQUEST['current']);
} elseif (!empty($_POST['current'])) {
return intval($_POST['current']);
} elseif (!empty($_GET['current'])) {
return intval($_GET['current']);
} elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid
$start = intval($_GET['start']);
$length = intval($_GET['length']);
if (!empty($start) && !empty($length)) {
return floor($start / $length) + 1;
}
}
return 1;
}
function getRowCount($default = 1000) {
global $global;
if (!empty($_REQUEST['rowCount'])) {
$defaultN = intval($_REQUEST['rowCount']);
} elseif (!empty($_POST['rowCount'])) {
$defaultN = intval($_POST['rowCount']);
} elseif (!empty($_GET['rowCount'])) {
$defaultN = intval($_GET['rowCount']);
} elseif (!empty($_REQUEST['length'])) {
$defaultN = intval($_REQUEST['length']);
} elseif (!empty($_POST['length'])) {
$defaultN = intval($_POST['length']);
} elseif (!empty($_GET['length'])) {
$defaultN = intval($_GET['length']);
} elseif (!empty($global['rowCount'])) {
$defaultN = intval($global['rowCount']);
}
return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default;
}
function getSearchVar() {
if (!empty($_REQUEST['search'])) {
return $_REQUEST['search'];
} elseif (!empty($_REQUEST['q'])) {
return $_REQUEST['q'];
}
if (!empty($_REQUEST['searchPhrase'])) {
return $_REQUEST['searchPhrase'];
} elseif (!empty($_REQUEST['search']['value'])) {
return $_REQUEST['search']['value'];
}
return "";
}
$cleanSearchHistory = "";
function cleanSearchVar() {
global $cleanSearchHistory;
$search = getSearchVar();
if (!empty($search)) {
$cleanSearchHistory = $search;
}
$searchIdex = array('q', 'searchPhrase', 'search');
foreach ($searchIdex as $value) {
unset($_REQUEST[$value]);
unset($_POST[$value]);
unset($_GET[$value]);
}
}
function reloadSearchVar() {
global $cleanSearchHistory;
$_REQUEST['search'] = $cleanSearchHistory;
if (empty($_GET['search'])) {
$_GET['search'] = $cleanSearchHistory;
}
if (empty($_POST['search'])) {
$_POST['search'] = $cleanSearchHistory;
}
}
function wget($url, $filename, $debug = false) {
if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) {
return false;
}
if (wgetIsLocked($url)) {
if ($debug) {
_error_log("wget: ERROR the url is already downloading $url, $filename");
}
return false;
}
wgetLock($url);
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$content = file_get_contents($url);
if (!empty($content) && file_put_contents($filename, $content) > 100) {
wgetRemoveLock($url);
return true;
}
wgetRemoveLock($url);
return false;
}
$cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate";
if ($debug) {
_error_log("wget Start ({$cmd}) ");
}
//echo $cmd;
exec($cmd);
wgetRemoveLock($url);
if (!file_exists($filename)) {
_error_log("wget: ERROR the url does not download $url, $filename");
return false;
}
if (empty(filesize($filename))) {
_error_log("wget: ERROR the url download but is empty $url, $filename");
return true;
}
return false;
}
function wgetLockFile($url) {
return getTmpDir("YPTWget") . md5($url) . ".lock";
}
function wgetLock($url) {
$file = wgetLockFile($url);
return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX);
}
function wgetRemoveLock($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function getLockFile($name) {
return getTmpDir("YPTLockFile") . md5($name) . ".lock";
}
function setLock($name) {
$file = getLockFile($name);
return file_put_contents($file, time());
}
function isLock($name, $timeout = 60) {
$file = getLockFile($name);
if (file_exists($file)) {
$time = intval(file_get_contents($file));
if ($time + $timeout < time()) {
return false;
}
}
}
function removeLock($name) {
$filename = getLockFile($name);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function wgetIsLocked($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
$time = intval(file_get_contents($filename));
if (time() - $time > 36000) { // more then 10 hours
unlink($filename);
return false;
}
return true;
}
// due the some OS gives a fake is_writable response
function isWritable($dir) {
$dir = rtrim($dir, '/') . '/';
$file = $dir . uniqid();
$result = false;
$time = time();
if (@file_put_contents($file, $time)) {
if ($fileTime = @file_get_contents($file)) {
if ($fileTime == $time) {
$result = true;
}
}
}
@unlink($file);
return $result;
}
function _isWritable($dir) {
if (!isWritable($dir)) {
return false;
}
$tmpFile = "{$dir}" . uniqid();
$bytes = @file_put_contents($tmpFile, time());
@unlink($tmpFile);
return !empty($bytes);
}
function getTmpDir($subdir = "") {
global $global;
if (empty($_SESSION['getTmpDir'])) {
$_SESSION['getTmpDir'] = array();
}
if (empty($_SESSION['getTmpDir'][$subdir . "_"])) {
$tmpDir = sys_get_temp_dir();
if (empty($tmpDir) || !_isWritable($tmpDir)) {
$tmpDir = getVideosDir() . "cache/";
}
$tmpDir = rtrim($tmpDir, '/') . '/';
$tmpDir = "{$tmpDir}{$subdir}";
$tmpDir = rtrim($tmpDir, '/') . '/';
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
_session_start();
$_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir;
} else {
$tmpDir = $_SESSION['getTmpDir'][$subdir . "_"];
}
return $tmpDir;
}
function getTmpFile() {
return getTmpDir("tmpFiles") . uniqid();
}
function getMySQLDate() {
global $global;
$sql = "SELECT now() as time FROM configurations LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data['time'];
} else {
$row = false;
}
return $row;
}
function _file_put_contents($filename, $data, $flags = 0, $context = null) {
make_path($filename);
return file_put_contents($filename, $data, $flags, $context);
}
function html2plainText($html) {
$text = strip_tags($html);
$text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text));
return $text;
}
function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') {
if (empty($paceholder)) {
$paceholder = __("Password");
}
?>
>
>
data-toggle="tooltip" data-placement="left" title="">
" . PHP_EOL;
} else {
return __LINE__;
}
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
echo "Error 1 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
return false;
}
function _json_encode($object) {
if (empty($object)) {
return false;
}
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 1 Found: " . json_last_error_msg());
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 2 Found: " . json_last_error_msg());
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 3 Found: " . json_last_error_msg());
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
_error_log("_json_encode: Error 4 Found: " . json_last_error_msg());
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 5 Found: " . json_last_error_msg());
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
_error_log("_json_encode: Error 6 Found: " . json_last_error_msg());
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 7 Found: " . json_last_error_msg());
}
}
}
}
}
}
}
return $json;
}
// this will make sure the strring will fits in the database field
function _substr($string, $start, $length = null) {
// make sure the name is not chunked in case of multibyte string
if (function_exists("mb_strcut")) {
return mb_strcut($string, $start, $length, "UTF-8");
} else {
return substr($string, $start, $length);
}
}
function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") {
global $global, $advancedCustom;
if ($total < 2) {
return "";
}
$uid = md5($link);
if ($total < $maxVisible) {
$maxVisible = $total;
}
if (empty($link)) {
$link = getSelfURI();
if (preg_match("/(current=[0-9]+)/i", $link, $match)) {
$link = str_replace($match[1], "current={page}", $link);
} else {
$link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}';
}
}
if (empty($page)) {
$page = getCurrentPage();
}
$class = "";
if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) {
$class = "infiniteScrollPagination{$uid} hidden";
}
$pag = ' ';
if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) {
$content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php');
$pag .= str_replace(
array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'),
array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector),
$content
);
}
return $pag;
}
function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") {
global $global, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetShareMenu.php';
}
function getSharePopupButton($videos_id, $url = "", $title = "") {
global $global, $advancedCustom;
if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) {
return false;
}
$video['id'] = $videos_id;
include $global['systemRootPath'] . 'view/include/socialModal.php';
}
function forbiddenPage($message, $logMessage = false) {
global $global;
$_REQUEST['403ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/forbiddenPage.php';
exit;
}
-define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |
- E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
-register_shutdown_function('avidoeShutdown');
-
+define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |
+ E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
+if(!isCommandLineInterface()){
+ register_shutdown_function('avidoeShutdown');
+}
function avidoeShutdown() {
global $global;
$error = error_get_last();
- if($error && ($error['type'] & E_FATAL)){
+ if ($error && ($error['type'] & E_FATAL)) {
_error_log($error, AVideoLog::$ERROR);
include $global['systemRootPath'] . 'view/maintanance.html';
exit;
}
}
function videoNotFound($message, $logMessage = false) {
global $global;
$_REQUEST['404ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/videoNotFound.php';
exit;
}
function isForbidden() {
global $global;
if (!empty($global['isForbidden'])) {
return true;
}
return false;
}
function diskUsageBars() {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function getDomain() {
global $global;
if (empty($_SERVER['HTTP_HOST'])) {
$parse = parse_url($global['webSiteRootURL']);
return $parse['host'];
}
$domain = $_SERVER['HTTP_HOST'];
$domain = str_replace("www.", "", $domain);
$domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain;
return $domain;
}
/**
* It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc.
*
* From the IETF RFC4122:
* 8-4-4-4-12
* @return string
*/
function getDeviceID() {
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return "unknowDevice";
}
$cookieName = "yptDeviceID";
if (empty($_COOKIE[$cookieName])) {
if (empty($_GET[$cookieName])) {
$_GET[$cookieName] = uniqidV4();
}
if (empty($_SESSION[$cookieName])) {
_session_start();
$_SESSION[$cookieName] = $_GET[$cookieName];
} else {
$_GET[$cookieName] = $_SESSION[$cookieName];
}
if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) {
return "getDeviceIDError";
}
$_COOKIE[$cookieName] = $_GET[$cookieName];
return $_GET[$cookieName];
}
return $_COOKIE[$cookieName];
}
function uniqidV4() {
$randomString = openssl_random_pseudo_bytes(16);
$time_low = bin2hex(substr($randomString, 0, 4));
$time_mid = bin2hex(substr($randomString, 4, 2));
$time_hi_and_version = bin2hex(substr($randomString, 6, 2));
$clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2));
$node = bin2hex(substr($randomString, 10, 6));
/**
* Set the four most significant bits (bits 12 through 15) of the
* time_hi_and_version field to the 4-bit version number from
* Section 4.1.3.
* @see http://tools.ietf.org/html/rfc4122#section-4.1.3
*/
$time_hi_and_version = hexdec($time_hi_and_version);
$time_hi_and_version = $time_hi_and_version >> 4;
$time_hi_and_version = $time_hi_and_version | 0x4000;
/**
* Set the two most significant bits (bits 6 and 7) of the
* clock_seq_hi_and_reserved to zero and one, respectively.
*/
$clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;
return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
}
// guid
function _setcookie($cookieName, $value, $expires = 0) {
if (empty($expires)) {
if (empty($config) || !is_object($config)) {
$config = new Configuration();
}
$expires = time() + $config->getSession_timeout();
}
if (version_compare(phpversion(), '7.3', '>=')) {
$cookie_options = array(
'expires' => $expires,
'path' => '/',
'domain' => getDomain(),
'secure' => true,
'httponly' => false,
'samesite' => 'None');
return setcookie($cookieName, $value, $cookie_options);
} else {
return setcookie($cookieName, $value, (int) $expires, "/", getDomain());
}
}
function _unsetcookie($cookieName) {
$domain = getDomain();
$expires = strtotime("-10 years");
$value = "";
_setcookie($cookieName, $value, $expires);
setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires);
setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain));
setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", "." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", $domain);
setcookie($cookieName, $value, (int) $expires, "/");
setcookie($cookieName, $value, (int) $expires);
unset($_COOKIE[$cookieName]);
}
/**
* This function is not 100% but try to tell if the site is in an iFrame
* @global type $global
* @return boolean
*/
function isIframeInDifferentDomain() {
global $global;
if (!isIframe()) {
return false;
}
return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']);
}
function isIframe() {
global $global;
if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') {
return true;
}
if (empty($_SERVER['HTTP_REFERER'])) {
return false;
}
return true;
}
function getCredentialsURL() {
global $global;
return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1";
}
function gotToLoginAndComeBackHere($msg) {
global $global;
if (!empty($_GET['comebackhere'])) {
return false;
}
header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1");
exit;
}
function setAlertMessage($msg, $type = "msg") {
_session_start();
$_SESSION['YPTalertMessage'][] = array($msg, $type);
}
function setToastMessage($msg) {
setAlertMessage($msg, "toast");
}
function showAlertMessage() {
if (!empty($_SESSION['YPTalertMessage'])) {
foreach ($_SESSION['YPTalertMessage'] as $value) {
if (!empty($value[0])) {
if (empty($_GET[$value[1]])) {
$_GET[$value[1]] = array();
}
$_GET[$value[1]][] = $value[0];
}
}
_session_start();
unset($_SESSION['YPTalertMessage']);
}
$joinString = array('error', 'msg', 'success');
foreach ($joinString as $value) {
if (!empty($_GET[$value]) && is_array($_GET[$value])) {
$_GET[$value] = array_unique($_GET[$value]);
$newStr = array();
foreach ($_GET[$value] as $value2) {
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = implode(" ", $newStr);
}
}
$check = array('error', 'msg', 'success', 'toast');
foreach ($check as $value) {
if (!empty($_GET[$value])) {
if (is_array($_GET[$value])) {
$newStr = array();
foreach ($_GET[$value] as $key => $value2) {
$value2 = str_replace('"', "''", $value2);
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = $newStr;
} else {
$_GET[$value] = str_replace('"', "''", $_GET[$value]);
}
}
}
echo "/** showAlertMessage **/", PHP_EOL;
if (!empty($_GET['error'])) {
echo 'avideoAlertError("' . $_GET['error'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['msg'])) {
echo 'avideoAlertInfo("' . $_GET['msg'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['success'])) {
echo 'avideoAlertSuccess("' . $_GET['success'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['toast'])) {
if (!is_array($_GET['toast'])) {
$_GET['toast'] = array($_GET['toast']);
} else {
$_GET['toast'] = array_unique($_GET['toast']);
}
foreach ($_GET['toast'] as $key => $value) {
$hideAfter = strlen(strip_tags($value)) * 150;
if ($hideAfter < 3000) {
$hideAfter = 3000;
}
if ($hideAfter > 15000) {
$hideAfter = 15000;
}
echo '$.toast({
text: "' . $value . '",
hideAfter: ' . $hideAfter . ' // in milli seconds
});console.log("Toast Hide after ' . $hideAfter . '");';
}
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
echo PHP_EOL, "/** showAlertMessage END **/";
}
function getResolutionLabel($res) {
if ($res == 720) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 1080) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 1440) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 2160) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 4320) {
return "" . getResolutionText($res) . " ";
} else {
return '';
}
}
function getResolutionText($res) {
if ($res == 720) {
return "HD";
} elseif ($res == 1080) {
return "FHD";
} elseif ($res == 1440) {
return "FHD+";
} elseif ($res == 2160) {
return "4K";
} elseif ($res == 4320) {
return "8K";
} else {
return '';
}
}
// just realize the readdir is a lot faster then glob
function _glob($dir, $pattern) {
global $_glob;
if (empty($dir)) {
return array();
}
if (empty($_glob)) {
$_glob = array();
}
$name = md5($dir . $pattern);
if (isset($_glob[$name])) {
return $_glob[$name];
}
$dir = rtrim($dir, '/') . '/';
$array = array();
if ($handle = opendir($dir)) {
$count = 0;
while (false !== ($file_name = readdir($handle))) {
if (preg_match($pattern, $file_name)) {
$array[] = "{$dir}{$file_name}";
}
}
closedir($handle);
}
$_glob[$name] = $array;
return $array;
}
function globVideosDir($filename, $filesOnly = false) {
global $global;
if (empty($filename)) {
return array();
}
$cleanfilename = Video::getCleanFilenameFromFile($filename);
$pattern = "/{$cleanfilename}.*";
if (!empty($filesOnly)) {
$formats = getValidFormats();
$pattern .= ".(" . implode("|", $formats) . ")";
}
$pattern .= "/";
return _glob(getVideosDir() . "", $pattern);
}
function getValidFormats() {
$video = array('webm', 'mp4', 'm3u8');
$audio = array('mp3', 'ogg');
$image = array('jpg', 'gif', 'webp');
return array_merge($video, $audio, $image);
}
function isValidFormats($format) {
$format = str_replace(".", "", $format);
return in_array($format, getValidFormats());
}
function getTimerFromDates($startTime, $endTime = 0) {
if (!is_int($startTime)) {
$startTime = strtotime($startTime);
}
if (!is_int($endTime)) {
$endTime = strtotime($endTime);
}
if (empty($endTime)) {
$endTime = time();
}
$timer = abs($endTime - $startTime);
$uid = uniqid();
return " ";
}
function getServerClock() {
$id = uniqid();
$today = getdate();
$html = '00:00:00 ';
$html .= "";
return $html;
}
/**
* Xsendfile and FFMPEG are required for this feature
* @global type $global
* @param type $filepath
* @return boolean
*/
function downloadHLS($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("downloadHLS: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("downloadHLS was not possible");
}
$outputpath = $output['path'];
$outputfilename = $output['filename'];
if (!empty($_REQUEST['title'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\'));
} elseif (!empty($_REQUEST['file'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4";
} else {
$quoted = $outputfilename;
}
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("X-Sendfile: {$outputpath}");
exit;
}
function playHLSasMP4($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("playHLSasMP4: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("playHLSasMP4: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("playHLSasMP4 was not possible");
}
$outputpath = $output['path'];
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: video/mp4');
header('Content-Length: ' . filesize($outputpath));
header("X-Sendfile: {$outputpath}");
exit;
}
function m3u8ToMP4($input) {
$videosDir = getVideosDir();
$outputfilename = str_replace($videosDir, "", $input);
$parts = explode("/", $outputfilename);
$resolution = Video::getResolutionFromFilename($input);
$outputfilename = $parts[0] . "_{$resolution}_.mp4";
$outputpath = "{$videosDir}cache/downloads/{$outputfilename}";
make_path($outputpath);
if (empty($outputfilename)) {
_error_log("downloadHLS: empty outputfilename {$outputfilename}");
return false;
}
$filepath = escapeshellcmd($input);
$outputpath = escapeshellcmd($outputpath);
if (!file_exists($outputpath)) {
$command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 1 " . implode(PHP_EOL, $output));
$command = get_ffmpeg() . " -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 2 " . implode(PHP_EOL, $output));
return false;
}
}
}
return array('path' => $outputpath, 'filename' => $outputfilename);
}
function getSocialModal($videos_id, $url = "", $title = "") {
global $global;
$video['id'] = $videos_id;
$sharingUid = uniqid();
ob_start();
?>
$contents, 'id' => $sharingUid);
}
function getCroppie(
$buttonTitle,
$callBackJSFunction,
$resultWidth,
$resultHeight,
$viewportWidth = 0,
$boundary = 25,
$viewportHeight = 0
) {
global $global;
if (empty($viewportWidth)) {
$viewportWidth = $resultWidth;
}
$zoom = 0;
if (empty($viewportHeight)) {
$zoom = ($viewportWidth / $resultWidth);
$viewportHeight = $zoom * $resultHeight;
}
$boundaryWidth = $viewportWidth + $boundary;
$boundaryHeight = $viewportHeight + $boundary;
$uid = uniqid();
ob_start();
include $global['systemRootPath'] . 'objects/functionCroppie.php';
$contents = ob_get_contents();
ob_end_clean();
$callBackJSFunction = addcslashes($callBackJSFunction, "'");
return array(
"html" => $contents,
"id" => "croppie{$uid}",
"uploadCropObject" => "uploadCrop{$uid}",
"getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});",
"createCroppie" => "createCroppie{$uid}",
"restartCroppie" => "restartCroppie{$uid}"
);
}
function saveCroppieImage($destination, $postIndex = "imgBase64") {
if (empty($_POST[$postIndex])) {
return false;
}
$fileData = base64DataToImage($_POST[$postIndex]);
return file_put_contents($destination, $fileData);
}
function get_ffmpeg($ignoreGPU = false) {
global $global;
//return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" ';
//return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" ';
$ffmpeg = 'ffmpeg ';
if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) {
$ffmpeg .= ' --enable-nvenc ';
}
if (!empty($global['ffmpeg'])) {
$ffmpeg = "{$global['ffmpeg']}{$ffmpeg}";
}
return $ffmpeg;
}
function isHTMLPage($url) {
if ($type = getHeaderContentTypeFromURL($url)) {
if (preg_match('/text\/html/i', $type)) {
return true;
}
}
return false;
}
function getHeaderContentTypeFromURL($url) {
if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) {
return $type;
}
return false;
}
function canFullScreen() {
global $doNotFullScreen;
if (!empty($doNotFullScreen) || isSerie() || !isVideo()) {
return false;
}
return true;
}
function getTinyMCE($id) {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function pathToRemoteURL($filename) {
global $pathToRemoteURL, $global;
if (!isset($pathToRemoteURL)) {
$pathToRemoteURL = array();
}
if (isset($pathToRemoteURL[$filename])) {
return $pathToRemoteURL[$filename];
}
$url = $filename;
if (!file_exists($filename) || filesize($filename) < 1000) {
$fileName = getFilenameFromPath($filename);
if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) {
- $source = $yptStorage->getAddress("{$filename}");
+ $source = $yptStorage->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) {
- $source = $aws_s3->getAddress("{$filename}");
+ $source = $aws_s3->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) {
- $source = $bb_b2->getAddress("{$filename}");
+ $source = $bb_b2->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) {
- $source = $ftp->getAddress("{$filename}");
+ $source = $ftp->getAddress("{$fileName}");
$url = $source['url'];
}
}
if (empty($url)) {
$url = $filename;
}
+
+ //$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url);
+
$pathToRemoteURL[$filename] = $url;
return $url;
}
function getFilenameFromPath($path) {
global $global;
$fileName = str_replace(getVideosDir() . "", "", $path);
$fileName = Video::getCleanFilenameFromFile($fileName);
return $fileName;
}
function showCloseButton() {
global $global, $showCloseButtonIncluded;
if (!empty($showCloseButtonIncluded)) {
return false;
}
if (isSerie()) {
return false;
}
if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) {
if (!empty($obj->playVideoOnFullscreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) {
if (!empty($obj->playLiveInFullScreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (!empty($_REQUEST['showCloseButton'])) {
$showCloseButtonIncluded = 1;
include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php';
return true;
}
return false;
}
function getThemes() {
global $_getThemes, $global;
- if(isset($_getThemes)){
+ if (isset($_getThemes)) {
return $_getThemes;
}
$_getThemes = array();
foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) {
$fileEx = basename($filename, ".css");
$_getThemes[] = $fileEx;
}
return $_getThemes;
}
function getCurrentTheme() {
global $config;
- if(!empty($_COOKIE['customCSS'])){
+ if (!empty($_COOKIE['customCSS'])) {
return $_COOKIE['customCSS'];
}
return $config->getTheme();
}
/*
* $users_id="" or 0 means send messages to all users
* $users_id="-1" means send to no one
*/
-function sendSocketMessage($msg, $callbackJSFunction="", $users_id="-1"){
- if(AVideoPlugin::isEnabledByName('Socket')){
- if(!is_string($msg)){
+
+function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern="") {
+ if (AVideoPlugin::isEnabledByName('Socket')) {
+ if (!is_string($msg)) {
$msg = json_encode($msg);
}
- $obj = Socket::send($msg, $callbackJSFunction, $users_id);
- if($obj->error){
- _error_log("sendSocketMessage ".$obj->msg, AVideoLog::$ERROR);
+ $obj = Socket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern);
+ if ($obj->error) {
+ _error_log("sendSocketMessage " . $obj->msg, AVideoLog::$ERROR);
}
return $obj;
}
return false;
}
-function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction=""){
- if(!is_array($users_id)){
+function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") {
+ if (!is_array($users_id)) {
$users_id = array($users_id);
}
-
+
$resp = array();
foreach ($users_id as $value) {
$resp[] = sendSocketMessage($msg, $callbackJSFunction, $value);
}
-
+
return $resp;
}
-function sendSocketMessageToAll($msg, $callbackJSFunction=""){
- return sendSocketMessage($msg, $callbackJSFunction, "");
+function sendSocketMessageToAll($msg, $callbackJSFunction = "", $send_to_uri_pattern="") {
+ return sendSocketMessage($msg, $callbackJSFunction, "", $send_to_uri_pattern);
}
-function sendSocketMessageToNone($msg, $callbackJSFunction=""){
+
+function sendSocketMessageToNone($msg, $callbackJSFunction = "") {
return sendSocketMessage($msg, $callbackJSFunction, -1);
}
function execAsync($command) {
+ $command = escapeshellarg($command);
// If windows, else
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
- //$pid = system($command . " > NUL");
- pclose($pid = popen("start /B ". $command, "r"));
+ //echo $command;
+ //$pid = system("start /min ".$command. " > NUL");
+ $commandString = "start /B cmd /S /C " . $command . " > NUL";
+ pclose($pid = popen($commandString, "r"));
} else {
$pid = exec($command . " > /dev/null 2>&1 & echo $!; ");
}
return $pid;
}
-function killProcess($pid){
+function killProcess($pid) {
$pid = intval($pid);
- if(empty($pid)){
+ if (empty($pid)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
exec("taskkill /F /PID $pid");
} else {
exec("kill -9 $pid");
}
return true;
-}
\ No newline at end of file
+}
+
+function isURL200($url) {
+ //error_log("isURL200 checking URL {$url}");
+ $headers = @get_headers($url);
+ foreach ($headers as $value) {
+ if(
+ strpos($headers[0],'200') ||
+ strpos($headers[0],'302') ||
+ strpos($headers[0],'304')
+ ){
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/objects/security.php b/objects/security.php
index 01f86f002..aba33255d 100644
--- a/objects/security.php
+++ b/objects/security.php
@@ -1,135 +1,98 @@
$value) {
+ $_FILES[$key]['name'] = preg_replace('/[^a-z0-9.,()+& #-]/i', '', cleanString($_FILES[$key]['name']));
}
}
-if (!empty($_POST['base64Url'])) {
- if (!filter_var(base64_decode($_POST['base64Url']), FILTER_VALIDATE_URL)) {
- _error_log('base64Url attack ' . json_encode($_SERVER), AVideoLog::$SECURITY);
- exit;
- }
-}
+$scanVars = array('GET', 'POST', 'REQUEST');
-foreach ($filterURL as $key => $value) {
- if (!empty($_GET[$value])) {
- if (!filter_var($_GET[$value], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $_GET[$value])) {
- //_error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY);
- unset($_GET[$value]);
- } else {
- $_GET[$value] = str_replace(array("'",'"',"<",">"), array("","","",""), $_GET[$value]);
+foreach ($scanVars as $value) {
+ eval('$scanThis = &$_' . $value.';');
+ if (!empty($scanThis['base64Url'])) {
+ if (!filter_var(base64_decode($scanThis['base64Url']), FILTER_VALIDATE_URL)) {
+ _error_log('base64Url attack ' . json_encode($_SERVER), AVideoLog::$SECURITY);
+ exit;
}
}
- if (!empty($_POST[$value])) {
- if (!filter_var($_POST[$value], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $_POST[$value])) {
- _error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY);
- unset($_POST[$value]);
- } else {
- $_POST[$value] = str_replace(array("'",'"',"<",">"), array("","","",""), $_POST[$value]);
+
+ foreach ($filterURL as $key => $value) {
+ if (!empty($scanThis[$value])) {
+ if (!filter_var($scanThis[$value], FILTER_VALIDATE_URL) || !preg_match("/^http.*/i", $scanThis[$value])) {
+ //_error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY);
+ unset($scanThis[$value]);
+ } else {
+ $scanThis[$value] = str_replace(array("'", '"', "<", ">"), array("", "", "", ""), $scanThis[$value]);
+ }
}
}
-}
-if (!empty($_FILES)) {
- foreach ($_FILES as $key=>$value) {
- $_FILES[$key]['name'] = preg_replace('/[^a-z0-9.,()+& #-]/i', '', cleanString($_FILES[$key]['name']));
- }
-}
-foreach ($securityRemoveNonChars as $value) {
- if (!empty($_POST[$value])) {
- if (is_string($_POST[$value])) {
- $_POST[$value] = str_replace('/[^a-z0-9./]/i', '', trim($_POST[$value]));
- } elseif (is_array($_POST[$value])) {
- foreach ($_POST[$value] as $key => $value2) {
- if (is_string($_POST[$value][$key])) {
- $_POST[$value][$key] = str_replace('/[^a-z0-9./]/i', '', trim($_POST[$value][$key]));
+ foreach ($securityRemoveNonChars as $value) {
+ if (!empty($scanThis[$value])) {
+ if (is_string($scanThis[$value])) {
+ $scanThis[$value] = str_replace('/[^a-z0-9./]/i', '', trim($scanThis[$value]));
+ } elseif (is_array($scanThis[$value])) {
+ foreach ($scanThis[$value] as $key => $value2) {
+ if (is_string($scanThis[$value][$key])) {
+ $scanThis[$value][$key] = str_replace('/[^a-z0-9./]/i', '', trim($scanThis[$value][$key]));
+ }
}
}
}
}
- if (!empty($_GET[$value])) {
- if (is_string($_GET[$value])) {
- $_GET[$value] = str_replace('/[^a-z0-9./]/i', '', trim($_GET[$value]));
- } elseif (is_array($_GET[$value])) {
- foreach ($_GET[$value] as $key => $value2) {
- if (is_string($_GET[$value][$key])) {
- $_GET[$value][$key] = str_replace('/[^a-z0-9./]/i', '', trim($_GET[$value][$key]));
+
+
+ foreach ($securityRemoveSingleQuotes as $value) {
+ if (!empty($scanThis[$value])) {
+ if (is_string($scanThis[$value])) {
+ $scanThis[$value] = str_replace("'", "", trim($scanThis[$value]));
+ } elseif (is_array($scanThis[$value])) {
+ foreach ($scanThis[$value] as $key => $value2) {
+ if (is_string($scanThis[$value][$key])) {
+ $scanThis[$value][$key] = str_replace("'", "", trim($scanThis[$value][$key]));
+ }
}
}
}
}
-}
-foreach ($securityRemoveSingleQuotes as $value) {
- if (!empty($_POST[$value])) {
- if (is_string($_POST[$value])) {
- $_POST[$value] = str_replace("'", "", trim($_POST[$value]));
- } elseif (is_array($_POST[$value])) {
- foreach ($_POST[$value] as $key => $value2) {
- if (is_string($_POST[$value][$key])) {
- $_POST[$value][$key] = str_replace("'", "", trim($_POST[$value][$key]));
- }
- }
+ // all variables with _id at the end will be forced to be interger
+ foreach ($scanThis as $key => $value) {
+ if(preg_match('/_id$/i', $key)){
+ $scanThis[$key] = intval($value);
}
}
- if (!empty($_GET[$value])) {
- if (is_string($_GET[$value])) {
- $_GET[$value] = str_replace("'", "", trim($_GET[$value]));
- } elseif (is_array($_GET[$value])) {
- foreach ($_GET[$value] as $key => $value2) {
- if (is_string($_GET[$value][$key])) {
- $_GET[$value][$key] = str_replace("'", "", trim($_GET[$value][$key]));
- }
+
+ foreach ($securityFilterInt as $value) {
+ if (!empty($scanThis[$value])) {
+ if (strtolower($scanThis[$value]) === "true") {
+ $scanThis[$value] = 1;
+ } else {
+ $scanThis[$value] = intval($scanThis[$value]);
}
}
}
-}
-foreach ($securityFilterInt as $value) {
- if (!empty($_POST[$value])) {
- if (strtolower($_POST[$value])==="true") {
- $_POST[$value] = 1;
- } else {
- $_POST[$value] = intval($_POST[$value]);
+ foreach ($securityFilter as $value) {
+ if (!empty($scanThis[$value])) {
+ $scanThis[$value] = str_replace(array('\\', "--", "'", '"', """, "'", "%23", "%5c", "#"), array('', '', '', '', '', '', '', '', ''), xss_esc($scanThis[$value]));
}
}
- if (!empty($_GET[$value])) {
- if (strtolower($_GET[$value])==="true") {
- $_GET[$value] = 1;
- } else {
- $_GET[$value] = intval($_GET[$value]);
- }
- }
-}
-foreach ($securityFilter as $value) {
- if (!empty($_POST[$value])) {
- $_POST[$value] = str_replace(array("'", '"', """, "'"), array('', '', '', ''), xss_esc($_POST[$value]));
- }
- if (!empty($_GET[$value])) {
- $_GET[$value] = str_replace(array("'", '"', """, "'"), array('', '', '', ''), xss_esc($_GET[$value]));
- }
-}
-
-if (!empty($_GET['sort']) && is_array($_GET['sort'])) {
- foreach ($_GET['sort'] as $key => $value) {
- $_GET['sort'][xss_esc($key)] = strcasecmp($value, "ASC") === 0 ? "ASC" : "DESC";
- }
-}
-if (!empty($_POST['sort']) && is_array($_POST['sort'])) {
- foreach ($_POST['sort'] as $key => $value) {
- $_POST['sort'][xss_esc($key)] = strcasecmp($value, "ASC") === 0 ? "ASC" : "DESC";
+ if (!empty($scanThis['sort']) && is_array($scanThis['sort'])) {
+ foreach ($scanThis['sort'] as $key => $value) {
+ $scanThis['sort'][xss_esc($key)] = strcasecmp($value, "ASC") === 0 ? "ASC" : "DESC";
+ }
}
-}
+}
\ No newline at end of file
diff --git a/objects/video.php b/objects/video.php
index 342f18c4e..64dfa95d1 100644
--- a/objects/video.php
+++ b/objects/video.php
@@ -1,4047 +1,4060 @@
'active',
'i' => 'inactive',
'e' => 'encoding',
'x' => 'encoding error',
'd' => 'downloading',
'xmp4' => 'encoding mp4 error',
'xwebm' => 'encoding webm error',
'xmp3' => 'encoding mp3 error',
'xogg' => 'encoding ogg error',
'ximg' => 'get image error',
't' => 'transfering');
public static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma');
//ver 3.4
private $youtubeId;
public static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'image', 'zip', 'notfound', 'blockedUser');
public function __construct($title = "", $filename = "", $id = 0)
{
global $global;
$this->rotation = 0;
$this->zoom = 1;
if (!empty($id)) {
$this->load($id);
}
if (!empty($title)) {
$this->setTitle($title);
}
if (!empty($filename)) {
$this->filename = $filename;
}
}
public function addView($currentTime = 0)
{
global $global;
if (empty($this->id)) {
return false;
}
$sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
$obj = new stdClass();
$obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime);
$obj->videos_id = $this->id;
$this->views_count++;
AVideoPlugin::addView($this->id, $this->views_count);
return $obj;
}
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
public function updateViewsCount($total)
{
global $global;
if (empty($this->id)) {
return false;
}
$total = intval($total);
if ($total<0) {
return false;
}
$sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
return $insert_row;
}
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
public function addViewPercent($percent = 25)
{
global $global;
if (empty($this->id)) {
return false;
}
$sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
return true;
}
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
// allow users to count a view again in case it is refreshed
public static function unsetAddView($videos_id)
{
// allow users to count a view again in case it is refreshed
if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) {
_session_start();
unset($_SESSION['addViewCount'][$videos_id]);
}
}
public function load($id)
{
$video = self::getVideoLight($id);
if (empty($video)) {
return false;
}
foreach ($video as $key => $value) {
$this->$key = $value;
}
}
public function getEncoderURL()
{
return $this->encoderURL;
}
public function getFilepath()
{
return $this->filepath;
}
public function getFilesize()
{
return intval($this->filesize);
}
public function setEncoderURL($encoderURL)
{
if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) {
$this->encoderURL = $encoderURL;
}
}
public function setFilepath($filepath)
{
$this->filepath = $filepath;
}
public function setFilesize($filesize)
{
$this->filesize = intval($filesize);
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function getSites_id()
{
return $this->sites_id;
}
public function setSites_id($sites_id)
{
$this->sites_id = $sites_id;
}
public function getVideo_password()
{
return trim($this->video_password);
}
public function setVideo_password($video_password)
{
$this->video_password = trim($video_password);
}
public function save($updateVideoGroups = false, $allowOfflineUser = false)
{
global $advancedCustom;
global $global;
if (!User::isLogged() && !$allowOfflineUser) {
_error_log('Video::save permission denied to save');
return false;
}
if (empty($this->title)) {
$this->title = uniqid();
}
$this->clean_title = substr($this->clean_title, 0, 187);
if (empty($this->clean_title)) {
$this->setClean_title($this->title);
}
$this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id);
if (empty($this->status)) {
$this->status = 'e';
}
if (empty($this->type) || !in_array($this->type, self::$typeOptions)) {
$this->type = 'video';
}
if (empty($this->isSuggested)) {
$this->isSuggested = 0;
} else {
$this->isSuggested = 1;
}
if (empty($this->categories_id)) {
$p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory");
$category = Category::getCategoryDefault();
$categories_id = $category['id'];
if (empty($categories_id)) {
$categories_id = 'NULL';
}
if ($p) {
$this->categories_id = $p->getCategoryId();
} else {
$this->categories_id = $categories_id;
}
if (empty($this->categories_id)) {
$this->categories_id = $categories_id;
}
}
// check if category exists
$cat = new Category($this->categories_id);
if (empty($cat->getName())) {
$catDefault = Category::getCategoryDefault();
$this->categories_id = $catDefault['id'];
}
$this->setTitle($global['mysqli']->real_escape_string(trim($this->title)));
$this->description = ($global['mysqli']->real_escape_string($this->description));
if (forbiddenWords($this->title) || forbiddenWords($this->description)) {
return false;
}
if (empty($this->users_id)) {
$this->users_id = User::getId();
}
$this->next_videos_id = intval($this->next_videos_id);
if (empty($this->next_videos_id)) {
$this->next_videos_id = 'NULL';
}
$this->sites_id = intval($this->sites_id);
if (empty($this->sites_id)) {
$this->sites_id = 'NULL';
}
$this->serie_playlists_id = intval($this->serie_playlists_id);
if (empty($this->serie_playlists_id)) {
$this->serie_playlists_id = 'NULL';
}
if (empty($this->filename)) {
$this->filename = $this->type . "_" . uniqid();
}
$this->can_download = intval($this->can_download);
$this->can_share = intval($this->can_share);
$this->only_for_paid = intval($this->only_for_paid);
$this->filesize = intval($this->filesize);
$this->rate = floatval($this->rate);
if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) {
$this->videoLink = '';
if ($this->type == 'embed') {
$this->type = 'video';
}
}
if (!empty($this->id)) {
if (!$this->userCanManageVideo() && !$allowOfflineUser && !Permissions::canModerateVideos()) {
header('Content-Type: application/json');
die('{"error":"3 ' . __("Permission denied") . '"}');
}
$sql = "UPDATE videos SET title = '{$this->title}',clean_title = '{$this->clean_title}',"
. " filename = '{$this->filename}', categories_id = '{$this->categories_id}', status = '{$this->status}',"
. " description = '{$this->description}', duration = '{$this->duration}', type = '{$this->type}', videoDownloadedLink = '{$this->videoDownloadedLink}', youtubeId = '{$this->youtubeId}', videoLink = '{$this->videoLink}', next_videos_id = {$this->next_videos_id}, isSuggested = {$this->isSuggested}, users_id = {$this->users_id}, "
. " trailer1 = '{$this->trailer1}', trailer2 = '{$this->trailer2}', trailer3 = '{$this->trailer3}', rate = '{$this->rate}', can_download = '{$this->can_download}', can_share = '{$this->can_share}', only_for_paid = '{$this->only_for_paid}', rrating = '{$this->rrating}', externalOptions = '{$this->externalOptions}', sites_id = {$this->sites_id}, serie_playlists_id = {$this->serie_playlists_id} , video_password = '{$this->video_password}', "
. " encoderURL = '{$this->encoderURL}', filepath = '{$this->filepath}' , filesize = '{$this->filesize}' , modified = now()"
. " WHERE id = {$this->id}";
} else {
$sql = "INSERT INTO videos "
. "(title,clean_title, filename, users_id, categories_id, status, description, duration,type,videoDownloadedLink, next_videos_id, created, modified, videoLink, can_download, can_share, only_for_paid, rrating, externalOptions, sites_id, serie_playlists_id, video_password, encoderURL, filepath , filesize) values "
. "('{$this->title}','{$this->clean_title}', '{$this->filename}', {$this->users_id},{$this->categories_id}, '{$this->status}', '{$this->description}', '{$this->duration}', '{$this->type}', '{$this->videoDownloadedLink}', {$this->next_videos_id},now(), now(), '{$this->videoLink}', '{$this->can_download}', '{$this->can_share}','{$this->only_for_paid}', '{$this->rrating}', '$this->externalOptions', {$this->sites_id}, {$this->serie_playlists_id}, '{$this->video_password}', '{$this->encoderURL}', '{$this->filepath}', '{$this->filesize}')";
}
$insert_row = sqlDAL::writeSql($sql);
if ($insert_row) {
_error_log("Video::save ({$this->title}) Saved id = {$insert_row} ");
Category::clearCacheCount();
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
$this->id = $id;
// check if needs to add the video in a user group
$p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory");
if ($p) {
$updateVideoGroups = true;
$this->videoGroups = $p->getUserGroupsArray();
}
} else {
$id = $this->id;
}
ObjectYPT::deleteCache("getItemprop{$this->id}");
ObjectYPT::deleteCache("getLdJson{$this->id}");
ObjectYPT::deleteCache("getVideoTags{$this->id}");
self::deleteTagsAsync($this->id);
if ($updateVideoGroups) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
// update the user groups
UserGroups::updateVideoGroups($id, $this->videoGroups);
}
// I am not sure what is it for
//Video::autosetCategoryType($id);
if (!empty($this->old_categories_id)) {
//Video::autosetCategoryType($this->old_categories_id);
}
self::clearCache($this->id);
return $id;
}
_error_log('Video::save ' . $sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
return false;
}
/*
static function autosetCategoryType($catId) {
global $global, $config;
if ($config->currentVersionLowerThen('5.01')) {
return false;
}
$sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$catTypeCache = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
$videoFound = false;
$audioFound = false;
if ($catTypeCache) {
// 3 means auto
if ($catTypeCache['manualSet'] == "0") {
// start incremental search and save
$sql = "SELECT * FROM `videos` WHERE categories_id = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult as $row) {
if ($row['type'] == "audio") {
// echo "found audio";
$audioFound = true;
} else if ($row['type'] == "video") {
//echo "found video";
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT * FROM `categories` WHERE parentId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
//$tmpVid = $res->fetch_assoc();
foreach ($fullResult as $row) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($row['parentId']));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
// echo "found audio";
$audioFound = true;
} else if ($row['type'] == "video") {
//echo "found video";
$videoFound = true;
}
}
}
}
}
$sql = "UPDATE `category_type_cache` SET `type` = '";
if (($videoFound) && ($audioFound)) {
$sql .= "0";
} else if ($audioFound) {
$sql .= "1";
} else if ($videoFound) {
$sql .= "2";
} else {
$sql .= "0";
}
$sql .= "' WHERE `category_type_cache`.`categoryId` = ?;";
sqlDAL::writeSql($sql, "i", array($catId));
}
} else {
// start incremental search and save - and a lot of this redundant stuff in a method..
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} else if ($row['type'] == "video") {
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT parentId FROM `categories` WHERE parentId = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $cat) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($cat['parentId']));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} else if ($row['type'] == "video") {
$videoFound = true;
}
}
}
}
}
}
$sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$exist = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
$sqlType = 99;
if (($videoFound) && ($audioFound)) {
$sqlType = 0;
} else if ($audioFound) {
$sqlType = 1;
} else if ($videoFound) {
$sqlType = 2;
}
$values = array();
if (empty($exist)) {
$sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`) VALUES (?, ?);";
$values = array($catId, $sqlType);
} else {
$sql = "UPDATE `category_type_cache` SET `type` = ? WHERE `category_type_cache`.`categoryId` = ?;";
$values = array($sqlType, $catId);
}
sqlDAL::writeSql($sql, "ii", $values);
}
}
*/
// i would like to simplify the big part of the method above in this method, but won't work as i want.
public static function internalAutoset($catId, $videoFound, $audioFound)
{
global $config;
if ($config->currentVersionLowerThen('5.01')) {
return false;
}
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} elseif ($row['type'] == "video") {
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $cat) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($cat['parentId']));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult as $row) {
if ($row['type'] == 'audio') {
$audioFound = true;
} elseif ($row['type'] == 'video') {
$videoFound = true;
}
}
}
}
}
}
return array($videoFound, audioFound);
}
public function setClean_title($clean_title)
{
if (preg_match("/video-automatically-booked/i", $clean_title) && !empty($this->clean_title)) {
return false;
}
$this->clean_title = cleanURLName($clean_title);
}
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function getIsSuggested()
{
return $this->isSuggested;
}
public function setIsSuggested($isSuggested)
{
if (empty($isSuggested) || $isSuggested === "false") {
$this->isSuggested = 0;
} else {
$this->isSuggested = 1;
}
}
public function setStatus($status)
{
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? ";
$res = sqlDAL::writeSql($sql, 'si', array($status, $this->id));
if ($global['mysqli']->errno != 0) {
die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
self::deleteTagsAsync($this->id);
}
$this->status = $status;
}
public function setType($type, $force = true)
{
if ($force || empty($this->type)) {
$this->type = $type;
}
}
public function setRotation($rotation)
{
$saneRotation = intval($rotation) % 360;
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET rotation = '{$saneRotation}', modified = now() WHERE id = {$this->id} ";
$res = sqlDAL::writeSql($sql);
if ($global['mysqli']->errno != 0) {
die('Error on update Rotation: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
$this->rotation = $saneRotation;
}
public function getRotation()
{
return $this->rotation;
}
public function getUsers_id()
{
return $this->users_id;
}
public function setZoom($zoom)
{
$saneZoom = abs(floatval($zoom));
if ($saneZoom < 0.1 || $saneZoom > 10) {
die('Zoom level must be between 0.1 and 10');
}
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET zoom = '{$saneZoom}', modified = now() WHERE id = {$this->id} ";
$res = sqlDAL::writeSql($sql);
if ($global['mysqli']->errno != 0) {
die('Error on update Zoom: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
$this->zoom = $saneZoom;
}
public function getZoom()
{
return $this->zoom;
}
public static function getUserGroupsCanSeeSQL()
{
global $global;
if (Permissions::canModerateVideos()) {
return "";
}
$sql = " (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0 ";
if (User::isLogged()) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$userGroups = UserGroups::getUserGroups(User::getId());
$groups_id = array();
foreach ($userGroups as $value) {
$groups_id[] = $value['id'];
}
if (!empty($groups_id)) {
$sql = " (({$sql}) OR ((SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id AND users_groups_id IN ('" . implode("','", $groups_id) . "') ) > 0)) ";
}
}
return " AND " . $sql;
}
public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true)
{
global $global, $config, $advancedCustom;
if ($config->currentVersionLowerThen('5')) {
return false;
}
$status = str_replace("'", "", $status);
$id = intval($id);
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
}
}
$sql = "SELECT u.*, v.*, "
. " nv.title as next_title,"
. " nv.clean_title as next_clean_title,"
. " nv.filename as next_filename,"
. " nv.id as next_id,"
. " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description,c.nextVideoOrder as category_order, v.created as videoCreation, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes ";
if (User::isLogged()) {
$sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote ";
} else {
$sql .= ", 0 as myVote ";
}
$sql .= " FROM videos as v "
. "LEFT JOIN categories c ON categories_id = c.id "
. "LEFT JOIN users u ON v.users_id = u.id "
. "LEFT JOIN videos nv ON v.next_videos_id = nv.id "
. " WHERE 1=1 ";
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
if (!empty($id)) {
$sql .= " AND v.id = '$id' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($status == "viewable") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['catName'])) {
- $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
+ $catName = $global['mysqli']->real_escape_string($_GET['catName']);
+ $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))";
}
if (empty($id) && !empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
if (!empty($user['id'])) {
$sql .= " AND v.users_id = '{$user['id']}' ";
}
}
if (!empty($_GET['search'])) {
$_POST['searchPhrase'] = $_GET['search'];
}
if (!empty($_POST['searchPhrase'])) {
$searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR");
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames);
}
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
}
if (!$ignoreGroup) {
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
}
// replace random based on this
$firstClauseLimit = "";
if (empty($id)) {
if (empty($random) && !empty($_GET['videoName'])) {
$sql .= " AND v.clean_title = '{$_GET['videoName']}' ";
} elseif (!empty($random)) {
$sql .= " AND v.id != {$random} ";
$rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly));
$rand = ($rand - 2) < 0 ? 0 : $rand - 2;
$firstClauseLimit = "$rand, ";
//$sql .= " ORDER BY RAND() ";
} elseif ($suggestedOnly && empty($_GET['videoName']) && empty($_GET['search']) && empty($_GET['searchPhrase'])) {
$sql .= " AND v.isSuggested = 1 ";
$rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly));
$rand = ($rand - 2) < 0 ? 0 : $rand - 2;
$firstClauseLimit = "$rand, ";
//$sql .= " ORDER BY RAND() ";
} elseif (!empty($_GET['v']) && is_numeric($_GET['v'])) {
$vid = intval($_GET['v']);
$sql .= " AND v.id = {$vid} ";
} else {
$sql .= " ORDER BY v.Created DESC ";
}
}
if (strpos($sql, 'v.id IN') === false && strpos(strtolower($sql), 'limit') === false) {
$sql .= " LIMIT {$firstClauseLimit}1";
}
//echo $sql, " ";//exit;
$res = sqlDAL::readSql($sql);
$video = sqlDAL::fetchAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
if ($res != false) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
if (!empty($video)) {
$video['category'] = xss_esc_back($video['category']);
$video['groups'] = UserGroups::getVideoGroups($video['id']);
$video['title'] = UTF8encode($video['title']);
$video['description'] = UTF8encode($video['description']);
$video['progress'] = self::getVideoPogressPercent($video['id']);
$video['isFavorite'] = self::isFavorite($video['id']);
$video['isWatchLater'] = self::isWatchLater($video['id']);
$video['favoriteId'] = self::getFavoriteIdFromUser(User::getId());
$video['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId());
if (empty($video['filesize']) && ($video['type'] == "video" || $video['type'] == "audio")) {
$video['filesize'] = Video::updateFilesize($video['id']);
}
if (!$ignoreTags) {
$video['tags'] = self::getTags($video['id']);
}
if (!empty($video['externalOptions'])) {
$video['externalOptions'] = json_decode($video['externalOptions']);
} else {
$video['externalOptions'] = new stdClass();
}
$video['descriptionHTML'] = strip_tags($video['description']) === $video['description'] ? nl2br(textToLink(htmlentities($video['description']))) : $video['description'];
if (!$ignoreTags && AVideoPlugin::isEnabledByName("VideoTags")) {
$video['videoTags'] = Tags::getAllFromVideosId($video['id']);
$video['videoTagsObject'] = Tags::getObjectFromVideosId($video['id']);
}
unset($video['password']);
unset($video['recoverPass']);
}
} else {
$video = false;
}
return $video;
}
public static function getVideoLight($id)
{
global $global, $config;
$id = intval($id);
$sql = "SELECT * FROM videos WHERE id = '$id' LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
public static function getTotalVideosSizeFromUser($users_id)
{
global $global, $config;
$users_id = intval($users_id);
$sql = "SELECT sum(filesize) as total FROM videos WHERE 1=1 ";
if (!empty($users_id)) {
$sql .= " AND users_id = '$users_id'";
}
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return intval($video['total']);
}
public static function getTotalVideosFromUser($users_id)
{
global $global, $config;
$users_id = intval($users_id);
$sql = "SELECT count(*) as total FROM videos WHERE 1=1 ";
if (!empty($users_id)) {
$sql .= " AND users_id = '$users_id'";
}
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return intval($video['total']);
}
public static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false)
{
global $global;
if (empty($fileName)) {
return false;
}
$parts = explode("/", $fileName);
if (!empty($parts[0])) {
$fileName = $parts[0];
}
$fileName = self::getCleanFilenameFromFile($fileName);
$sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($fileName));
if ($res != false) {
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($video['id'])) {
return self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags);
}
}
return false;
}
public static function getVideoFromFileNameLight($fileName)
{
global $global;
$fileName = self::getCleanFilenameFromFile($fileName);
if (empty($fileName)) {
return false;
}
$sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($fileName), true);
if ($res != false) {
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
return false;
}
public static function getVideoFromCleanTitle($clean_title)
{
// for some reason in some servers (CPanel) we got the error "Error while sending QUERY packet centos on a select"
// even increasing the max_allowed_packet it only goes away when close and reopen the connection
global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort;
$global['mysqli']->close();
_mysql_connect();
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
$sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($clean_title));
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
return self::getVideo($video['id'], "", true, false, false, true);
//$video['groups'] = UserGroups::getVideoGroups($video['id']);
} else {
return false;
}
}
/**
*
* @global type $global
* @param type $status
* @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results
* @param type $ignoreGroup
* @param type $videosArrayId an array with videos to return (for filter only)
* @return boolean
*/
public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false)
{
global $global, $config, $advancedCustom;
if ($config->currentVersionLowerThen('5')) {
return false;
}
if (!empty($_POST['sort']['suggested'])) {
$suggestedOnly = true;
}
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$status = str_replace("'", "", $status);
$sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes "
. " FROM videos as v "
. " LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$uid = intval(User::getId());
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$uid = intval($showOnlyLoggedUserVideos);
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
TimeLogStart("video::getAllVideos::getAllVideosExcludeVideosIDArray");
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
TimeLogEnd("video::getAllVideos::getAllVideosExcludeVideosIDArray", __LINE__);
}
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'videoOnly') {
$sql .= " AND (v.type = 'video')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if ($status == "viewable") {
if (User::isLogged()) {
$sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))";
} else {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
}
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif ($status == "publicOnly") {
$sql .= " AND v.status = 'a' AND (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['catName'])) {
- $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
+ $catName = $global['mysqli']->real_escape_string($_GET['catName']);
+ $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))";
}
if (!empty($_GET['search'])) {
$_POST['searchPhrase'] = $_GET['search'];
}
if (!empty($_GET['modified'])) {
$_GET['modified'] = str_replace("'", "", $_GET['modified']);
$sql .= " AND v.modified >= '{$_GET['modified']}'";
}
if (!empty($_POST['searchPhrase'])) {
$searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR");
+ $searchFieldsNames = array('v.title');
+ $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames);
+ $searchFieldsNames = array('v.title');
+ $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
}
- $searchFieldsNames = array('v.title');
- $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
}
$sql .= AVideoPlugin::getVideoWhereClause();
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
$sql .= " ORDER BY RAND() ";
$sort = @$_POST['sort'];
unset($_POST['sort']);
$sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true);
if (strpos(strtolower($sql), 'limit') === false) {
$sql .= " LIMIT 60 ";
}
$_POST['sort'] = $sort;
} elseif (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) {
$sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true);
} else {
unset($_POST['sort']['trending']);
unset($_GET['sort']['trending']);
$rows = array();
if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) {
$rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly);
}
$ids = array();
foreach ($rows as $row) {
$ids[] = $row['id'];
}
if (!empty($ids)) {
$sql .= " ORDER BY FIND_IN_SET(v.id, '" . implode(",", $ids) . "') DESC, likes DESC ";
} else {
$sql .= " ORDER BY likes DESC ";
}
$sql .= ObjectYPT::getSqlLimit();
}
if (strpos(strtolower($sql), 'limit') === false) {
if (!empty($_GET['limitOnceToOne'])) {
$sql .= " LIMIT 1";
unset($_GET['limitOnceToOne']);
}else{
$_REQUEST['rowCount'] = getRowCount();
if (!empty($_REQUEST['rowCount'])) {
$sql .= " LIMIT {$_REQUEST['rowCount']}";
} else {
_error_log("getAllVideos without limit " . json_encode(debug_backtrace()));
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = 100;
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
}
}
//echo $sql;exit;
//_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
$videos = array();
if ($res != false) {
require_once 'userGroups.php';
TimeLogStart("video::getAllVideos foreach");
foreach ($fullData as $row) {
unset($row['password']);
unset($row['recoverPass']);
if (!self::canEdit($row['id'])) {
if (!empty($row['video_password'])) {
$row['video_password'] = 1;
} else {
$row['video_password'] = 0;
}
}
if ($getStatistcs) {
TimeLogStart("video::getAllVideos getStatistcs");
$previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days"));
$previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days"));
$today = date('Y-m-d 23:59:59');
$row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']);
$row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today);
$row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today);
$row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today);
$row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true);
TimeLogEnd("video::getAllVideos getStatistcs", __LINE__);
}
TimeLogStart("video::getAllVideos otherInfo");
$otherInfocachename = "otherInfo{$row['id']}";
$otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename), 600);
if (empty($otherInfo)) {
$otherInfo = array();
$otherInfo['category'] = xss_esc_back($row['category']);
$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']);
$otherInfo['tags'] = self::getTags($row['id']);
$otherInfo['title'] = UTF8encode($row['title']);
$otherInfo['description'] = UTF8encode($row['description']);
$otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']);
if (empty($row['filesize'])) {
$otherInfo['filesize'] = Video::updateFilesize($row['id']);
}
ObjectYPT::setCache($otherInfocachename, $otherInfo);
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['progress'] = self::getVideoPogressPercent($row['id']);
$row['isFavorite'] = self::isFavorite($row['id']);
$row['isWatchLater'] = self::isWatchLater($row['id']);
$row['favoriteId'] = self::getFavoriteIdFromUser(User::getId());
$row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId());
TimeLogEnd("video::getAllVideos otherInfo", __LINE__);
TimeLogStart("video::getAllVideos getAllVideosArray");
$row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id']));
TimeLogEnd("video::getAllVideos getAllVideosArray", __LINE__);
$videos[] = $row;
}
TimeLogEnd("video::getAllVideos foreach", __LINE__);
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
public static function htmlDescription($description)
{
if (strip_tags($description) != $description) {
return $description;
} else {
return nl2br(textToLink(htmlentities($description)));
}
}
public static function isFavorite($videos_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::isVideoOnFavorite($videos_id, User::getId());
}
return false;
}
public static function isSerie($videos_id)
{
$v = new Video("", "", $videos_id);
return !empty($v->getSerie_playlists_id());
}
public static function isWatchLater($videos_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::isVideoOnWatchLater($videos_id, User::getId());
}
return false;
}
public static function getFavoriteIdFromUser($users_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::getFavoriteIdFromUser($users_id);
}
return false;
}
public static function getWatchLaterIdFromUser($users_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::getWatchLaterIdFromUser($users_id);
}
return false;
}
public static function updateFilesize($videos_id)
{
global $config;
if ($config->currentVersionLowerThen('8.5')) {
return false;
}
TimeLogStart("Video::updateFilesize {$videos_id}");
ini_set('max_execution_time', 300); // 5
set_time_limit(300);
$video = new Video("", "", $videos_id);
$filename = $video->getFilename();
if (empty($filename) || !($video->getType() == "video" || $video->getType() == "audio" || $video->getType() == "zip" || $video->getType() == "image")) {
//_error_log("updateFilesize: Not updated, this filetype is ".$video->getType());
return false;
}
$filesize = getUsageFromFilename($filename);
if (empty($filesize)) {
$obj = AVideoPlugin::getObjectDataIfEnabled("DiskUploadQuota");
if (!empty($obj->deleteVideosWith0Bytes)) {
try {
_error_log("updateFilesize: DELETE videos_id=$videos_id filename=$filename filesize=$filesize");
return $video->delete();
} catch (Exception $exc) {
_error_log("updateFilesize: ERROR " . $exc->getTraceAsString());
return false;
}
}
}
if ($video->getFilesize() == $filesize) {
//_error_log("updateFilesize: No need to update videos_id=$videos_id filename=$filename filesize=$filesize");
return $filesize;
}
$video->setFilesize($filesize);
TimeLogEnd("Video::updateFilesize {$videos_id}", __LINE__);
if ($video->save(false, true)) {
_error_log("updateFilesize: videos_id=$videos_id filename=$filename filesize=$filesize");
return $filesize;
} else {
_error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize");
return false;
}
}
public static function getAllVideosAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true)
{
global $global, $advancedCustom;
$return = array();
$users_id = User::getId();
$get = json_encode(@$_GET);
$post = json_encode(@$_POST);
$md5 = md5("{$users_id}{$get}{$post}{$status}{$showOnlyLoggedUserVideos}{$ignoreGroup}" . implode("_", $videosArrayId) . "{$getStatistcs}{$showUnlisted}{$activeUsersOnly}");
$path = getCacheDir() . "getAllVideosAsync/";
make_path($path);
$cacheFileName = "{$path}{$md5}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName) || filesize($cacheFileName) === 0) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getAllVideosAsync.php' '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup' '" . json_encode($videosArrayId) . "' '$getStatistcs' '$showUnlisted' '$activeUsersOnly' '{$get}' '{$post}' '{$cacheFileName}'");
_error_log("getAllVideosAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return object_to_array($return);
}
/**
* Same as getAllVideos() method but a lighter query
* @global type $global
* @global type $config
* @param type $showOnlyLoggedUserVideos
* @return boolean
*/
public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false)
{
global $global, $config;
if ($config->currentVersionLowerThen('5')) {
return false;
}
$status = str_replace("'", "", $status);
$sql = "SELECT v.* "
. " FROM videos as v "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$sql .= " AND v.users_id = '" . User::getId() . "'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'";
}
if ($status == "viewable") {
if (User::isLogged()) {
$sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))";
} else {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
}
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$sql .= " AND v.users_id = '{$user['id']}' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
$sql .= " ORDER BY RAND() ";
}
if (strpos(strtolower($sql), 'limit') === false) {
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount'];
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
//echo $sql;
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
$videos = array();
if ($res != false) {
foreach ($fullData as $row) {
if (empty($row['filesize'])) {
$row['filesize'] = Video::updateFilesize($row['id']);
}
$videos[] = $row;
}
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
public static function getTotalVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false)
{
global $global, $config;
if ($config->currentVersionLowerThen('5')) {
return false;
}
if (!empty($_POST['sort']['suggested'])) {
$suggestedOnly = true;
}
$status = str_replace("'", "", $status);
$cn = "";
if (!empty($_GET['catName'])) {
$cn .= ", c.clean_name as cn";
}
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$sql = "SELECT v.users_id, v.type, v.id, v.title,v.description, c.name as category {$cn} "
. "FROM videos v "
. "LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($status == "viewable") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$sql .= " AND v.users_id = '" . User::getId() . "'";
} elseif (is_int($showOnlyLoggedUserVideos)) {
$sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'";
}
if (!empty($_GET['catName'])) {
- $sql .= " AND c.clean_name = '{$_GET['catName']}'";
+ $catName = $global['mysqli']->real_escape_string($_GET['catName']);
+ $sql .= " AND c.clean_name = '{$catName}'";
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if (!$ignoreGroup) {
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
}
if (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if (!empty($_POST['searchPhrase'])) {
$searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR");
+ $searchFieldsNames = array('v.title');
+ $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames);
+ $searchFieldsNames = array('v.title');
+ $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
}
-
- $searchFieldsNames = array('v.title');
- $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
}
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
}
$res = sqlDAL::readSql($sql);
$numRows = sqlDal::num_rows($res);
sqlDAL::close($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($numRows) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getTotalVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
return $numRows;
}
public static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array())
{
$obj = new stdClass();
$obj->likes = 0;
$obj->disLikes = 0;
$obj->views_count = 0;
$obj->total_minutes = 0;
$videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId);
foreach ($videos as $value) {
$obj->likes += intval($value['likes']);
$obj->disLikes += intval($value['dislikes']);
$obj->views_count += intval($value['views_count']);
$obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60);
}
return $obj;
}
public static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false)
{
global $global, $advancedCustom;
$path = getCacheDir() . "getTotalVideosInfo/";
make_path($path);
$cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}";
$return = array();
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' "
. " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', "
. " '$getStatistcs', '$cacheFileName'");
//_error_log("getTotalVideosInfoAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return $return;
}
public static function getViewableStatus($showUnlisted = false)
{
/**
a = active
i = inactive
e = encoding
x = encoding error
d = downloading
u = unlisted
xmp4 = encoding mp4 error
xwebm = encoding webm error
xmp3 = encoding mp3 error
xogg = encoding ogg error
*/
$viewable = array('a', 'xmp4', 'xwebm', 'xmp3', 'xogg');
if ($showUnlisted) {
$viewable[] = "u";
} elseif (!empty($_GET['videoName'])) {
$post = $_POST;
if (self::isOwnerFromCleanTitle($_GET['videoName']) || Permissions::canModerateVideos()) {
$viewable[] = "u";
}
$_POST = $post;
}
return $viewable;
}
public static function getVideoConversionStatus($filename)
{
global $global;
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isLogged()) {
die("Only logged users can upload");
}
$object = new stdClass();
foreach (self::$types as $value) {
$progressFilename = self::getStoragePathFromFileName($filename). "progress_{$value}.txt";
$content = @url_get_contents($progressFilename);
$object->$value = new stdClass();
if (!empty($content)) {
$object->$value = self::parseProgress($content);
} else {
}
if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) {
$video = self::getVideoFromFileName($filename);
//var_dump($video, $filename);
if (!empty($video)) {
$object->$value->progress = self::$statusDesc[$video['status']];
}
}
$object->$value->filename = $progressFilename;
}
return $object;
}
private static function parseProgress($content)
{
//get duration of source
$obj = new stdClass();
$obj->duration = 0;
$obj->currentTime = 0;
$obj->progress = 0;
//var_dump($content);exit;
preg_match("/Duration: (.*?), start:/", $content, $matches);
if (!empty($matches[1])) {
$rawDuration = $matches[1];
//rawDuration is in 00:00:00.00 format. This converts it to seconds.
$ar = array_reverse(explode(":", $rawDuration));
$duration = floatval($ar[0]);
if (!empty($ar[1])) {
$duration += intval($ar[1]) * 60;
}
if (!empty($ar[2])) {
$duration += intval($ar[2]) * 60 * 60;
}
//get the time in the file that is already encoded
preg_match_all("/time=(.*?) bitrate/", $content, $matches);
$rawTime = array_pop($matches);
//this is needed if there is more than one match
if (is_array($rawTime)) {
$rawTime = array_pop($rawTime);
}
//rawTime is in 00:00:00.00 format. This converts it to seconds.
$ar = array_reverse(explode(":", $rawTime));
$time = floatval($ar[0]);
if (!empty($ar[1])) {
$time += intval($ar[1]) * 60;
}
if (!empty($ar[2])) {
$time += intval($ar[2]) * 60 * 60;
}
if (!empty($duration)) {
//calculate the progress
$progress = round(($time / $duration) * 100);
} else {
$progress = 'undefined';
}
$obj->duration = $duration;
$obj->currentTime = $time;
$obj->progress = $progress;
}
return $obj;
}
public function delete($allowOfflineUser = false)
{
if (!$allowOfflineUser && !$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($this->id)) {
$this->removeNextVideos($this->id);
$this->removeTrailerReference($this->id);
$this->removeCampaign($this->id);
$video = self::getVideoLight($this->id);
$sql = "DELETE FROM videos WHERE id = ?";
} else {
return false;
}
$resp = sqlDAL::writeSql($sql, "i", array($this->id));
if ($resp == false) {
_error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
return false;
} else {
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
$ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage');
$YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage');
if (!empty($aws_s3)) {
$aws_s3->removeFiles($video['filename']);
}
if (!empty($bb_b2)) {
$bb_b2->removeFiles($video['filename']);
}
if (!empty($ftp)) {
$ftp->removeFiles($video['filename']);
}
if (!empty($YPTStorage)) {
$YPTStorage->removeFiles($video['filename'], $video['sites_id']);
}
$this->removeFiles($video['filename']);
self::deleteThumbs($video['filename']);
}
return $resp;
}
private function removeNextVideos($videos_id)
{
if (!$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($videos_id)) {
$sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?";
sqlDAL::writeSql($sql, "s", array($videos_id));
} else {
return false;
}
return true;
}
private function removeTrailerReference($videos_id)
{
if (!$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($videos_id)) {
$videoURL = self::getLink($videos_id, '', true);
$sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
$sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
$sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
} else {
return false;
}
return true;
}
private function removeCampaign($videos_id)
{
if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) {
if (!empty($this->id)) {
$sql = "DELETE FROM vast_campaigns_has_videos ";
$sql .= " WHERE videos_id = ?";
$global['lastQuery'] = $sql;
return sqlDAL::writeSql($sql, "i", array($videos_id));
}
}
return false;
}
private function removeFiles($filename)
{
if (empty($filename)) {
return false;
}
global $global;
$file = self::getStoragePath()."original_{$filename}";
$this->removeFilePath($file);
$files = self::getStoragePath()."{$filename}";
$this->removeFilePath($files);
}
private function removeFilePath($filePath)
{
if (empty($filePath)) {
return false;
}
// Streamlined for less coding space.
$files = glob("{$filePath}*");
foreach ($files as $file) {
if (file_exists($file)) {
if (is_dir($file)) {
self::rrmdir($file);
} else {
@unlink($file);
}
}
}
}
private static function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir . "/" . $object)) {
self::rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
rmdir($dir);
}
}
public function setDescription($description)
{
global $global, $advancedCustom;
if (empty($advancedCustom->disableHTMLDescription)) {
$articleObj = AVideoPlugin::getObjectData('Articles');
$configPuri = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($configPuri);
if (empty($articleObj->allowAttributes)) {
$configPuri->set('HTML.AllowedAttributes', array('a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height')); // remove all attributes except a.href
$configPuri->set('Attr.AllowedFrameTargets', array('_blank'));
}
if (empty($articleObj->allowAttributes)) {
$configPuri->set('CSS.AllowedProperties', array()); // remove all CSS
}
$configPuri->set('AutoFormat.RemoveEmpty', true); // remove empty elements
$pure = $purifier->purify($description);
$parts = explode("", $pure);
if (!empty($parts[1])) {
$parts = explode("", $parts[1]);
}
$this->description = $parts[0];
} else {
$this->description = strip_tags(br2nl($description));
}
//var_dump($this->description, $description, $parts);exit;
}
public function setCategories_id($categories_id)
{
if (!Category::userCanAddInCategory($categories_id)) {
return false;
}
// to update old cat as well when auto..
if (!empty($this->categories_id)) {
$this->old_categories_id = $this->categories_id;
}
$this->categories_id = $categories_id;
}
public static function getCleanDuration($duration = "")
{
if (empty($duration)) {
if (!empty($this) && !empty($this->duration)) {
$durationParts = explode(".", $this->duration);
} else {
return "00:00:00";
}
} else {
$durationParts = explode(".", $duration);
}
if (empty($durationParts[0])) {
return "00:00:00";
} else {
$duration = $durationParts[0];
$durationParts = explode(':', $duration);
if (count($durationParts) == 1) {
return '0:00:' . static::addZero($durationParts[0]);
} elseif (count($durationParts) == 2) {
return '0:' . static::addZero($durationParts[0]) . ':' . static::addZero($durationParts[1]);
}
return $duration;
}
}
private static function addZero($str)
{
if (intval($str) < 10) {
return '0' . intval($str);
}
return $str;
}
public static function getItemPropDuration($duration = '')
{
$duration = static::getCleanDuration($duration);
$parts = explode(':', $duration);
$duration = 'PT' . intval($parts[0]) . 'H' . intval($parts[1]) . 'M' . intval($parts[2]) . 'S';
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
return $duration;
}
public static function getItemDurationSeconds($duration = '')
{
if ($duration == "EE:EE:EE") {
return 0;
}
$duration = static::getCleanDuration($duration);
$parts = explode(':', $duration);
return intval($parts[0] * 60 * 60) + intval($parts[1] * 60) + intval($parts[2]);
}
public static function getDurationFromFile($file)
{
global $global;
// get movie duration HOURS:MM:SS.MICROSECONDS
if (!file_exists($file)) {
_error_log('{"status":"error", "msg":"getDurationFromFile ERROR, File (' . $file . ') Not Found"}');
return "EE:EE:EE";
}
// Initialize getID3 engine
$getID3 = new getID3;
// Analyze file and store returned data in $ThisFileInfo
$ThisFileInfo = $getID3->analyze($file);
return static::getCleanDuration(@$ThisFileInfo['playtime_string']);
}
public static function getResolution($file)
{
global $videogetResolution;
if (!isset($videogetResolution)) {
$videogetResolution = array();
}
if (isset($videogetResolution[$file])) {
return $videogetResolution[$file];
}
if (
AVideoPlugin::isEnabledByName("Blackblaze_B2") ||
AVideoPlugin::isEnabledByName("AWS_S3") ||
AVideoPlugin::isEnabledByName("FTP_Storage") ||
AVideoPlugin::isEnabledByName("YPTStorage")
|| !file_exists($file)) {
$videogetResolution[$file] = 0;
return 0;
}
global $global;
if (preg_match("/.m3u8$/i", $file) && AVideoPlugin::isEnabledByName('VideoHLS') && method_exists(new VideoHLS(), 'getHLSHigestResolutionFromFile')) {
$videogetResolution[$file] = VideoHLS::getHLSHigestResolutionFromFile($file);
} else {
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($file);
$videogetResolution[$file] = intval(@$ThisFileInfo['video']['resolution_y']);
}
return $videogetResolution[$file];
}
public static function getHLSDurationFromFile($file)
{
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (empty($plugin)) {
return 0;
}
return VideoHLS::getHLSDurationFromFile($file);
}
public function updateHLSDurationIfNeed()
{
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (empty($plugin)) {
return false;
}
return VideoHLS::updateHLSDurationIfNeed($this);
}
public function updateDurationIfNeed($fileExtension = ".mp4")
{
global $global;
$source = self::getSourceFile($this->filename, $fileExtension, true);
$file = $source['path'];
if (!empty($this->id) && $this->duration == "EE:EE:EE" && file_exists($file)) {
$this->duration = Video::getDurationFromFile($file);
_error_log("Duration Updated: " . json_encode($this));
$sql = "UPDATE videos SET duration = ?, modified = now() WHERE id = ?";
$res = sqlDAL::writeSql($sql, "si", array($this->duration, $this->id));
return $this->id;
} else {
_error_log("Do not need update duration: " . json_encode($this));
return false;
}
}
public function getFilename()
{
return $this->filename;
}
public function getStatus()
{
return $this->status;
}
public function getId()
{
return $this->id;
}
public function getVideoDownloadedLink()
{
return $this->videoDownloadedLink;
}
public function setVideoDownloadedLink($videoDownloadedLink)
{
$this->videoDownloadedLink = $videoDownloadedLink;
}
public static function isLandscape($pathFileName)
{
global $config;
// get movie duration HOURS:MM:SS.MICROSECONDS
if (!file_exists($pathFileName)) {
echo '{"status":"error", "msg":"isLandscape ERROR, File (' . $pathFileName . ') Not Found"}';
return true;
}
eval('$cmd="' . $config->getExiftool() . '";');
$resp = true; // is landscape by default
exec($cmd . ' 2>&1', $output, $return_val);
if ($return_val !== 0) {
$resp = true;
} else {
$w = 1;
$h = 0;
$rotation = 0;
foreach ($output as $value) {
preg_match("/Image Size.*:[^0-9]*([0-9]+x[0-9]+)/i", $value, $match);
if (!empty($match)) {
$parts = explode("x", $match[1]);
$w = $parts[0];
$h = $parts[1];
}
preg_match("/Rotation.*:[^0-9]*([0-9]+)/i", $value, $match);
if (!empty($match)) {
$rotation = $match[1];
}
}
if ($rotation == 0) {
if ($w > $h) {
$resp = true;
} else {
$resp = false;
}
} else {
if ($w < $h) {
$resp = true;
} else {
$resp = false;
}
}
}
//var_dump($cmd, $w, $h, $rotation, $resp);exit;
return $resp;
}
public function userCanManageVideo()
{
global $advancedCustomUser;
if (Permissions::canAdminVideos()) {
return true;
}
if (empty($this->users_id) || !User::canUpload()) {
return false;
}
// if you not admin you can only manager yours video
$users_id = $this->users_id;
if ($advancedCustomUser->userCanChangeVideoOwner) {
$video = new Video("", "", $this->id); // query again to make sure the user is not changing the owner
$users_id = $video->getUsers_id();
}
if ($users_id != User::getId()) {
return false;
}
return true;
}
public function getVideoGroups()
{
return $this->videoGroups;
}
public function setVideoGroups($userGroups)
{
if (is_array($userGroups)) {
$this->videoGroups = $userGroups;
}
}
/**
*
* @param type $user_id
* text
* label Default Primary Success Info Warning Danger
*/
public static function getTags($video_id, $type = "")
{
global $advancedCustom, $videos_getTags;
if (empty($videos_getTags)) {
$videos_getTags = array();
}
$name = "{$video_id}_{$type}";
if (!empty($videos_getTags[$name])) {
return $videos_getTags[$name];
}
if (empty($advancedCustom->AsyncJobs)) {
$videos_getTags[$name] = self::getTags_($video_id, $type);
return $videos_getTags[$name];
} else {
$tags = self::getTagsAsync($video_id, $type);
foreach ($tags as $key => $value) {
if (is_array($value)) {
$tags[$key] = (object) $value;
}
}
$videos_getTags[$name] = $tags;
return $tags;
}
}
public static function getTags_($video_id, $type = "")
{
global $advancedCustom, $advancedCustomUser;
if (empty($advancedCustom)) {
$advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser");
}
if (empty($advancedCustom)) {
$advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced");
}
$currentPage = getCurrentPage();
$rowCount = getRowCount();
$_REQUEST['current'] = 1;
$_REQUEST['rowCount'] = 1000;
$video = new Video("", "", $video_id);
$tags = array();
if (empty($type) || $type === "paid") {
$objTag = new stdClass();
$objTag->label = __("Paid Content");
if (!empty($advancedCustom->paidOnlyShowLabels)) {
if (!empty($video->getOnly_for_paid())) {
$objTag->type = "warning";
$objTag->text = $advancedCustom->paidOnlyLabel;
} else {
$objTag->type = "success";
$objTag->text = $advancedCustom->paidOnlyFreeLabel;
}
} else {
$ppv = AVideoPlugin::getObjectDataIfEnabled("PayPerView");
if ($advancedCustomUser->userCanProtectVideosWithPassword && !empty($video->getVideo_password())) {
$objTag->type = "danger";
$objTag->text = ' ';
} elseif (!empty($video->getOnly_for_paid())) {
$objTag->type = "warning";
$objTag->text = $advancedCustom->paidOnlyLabel;
} elseif ($ppv && PayPerView::isVideoPayPerView($video_id)) {
if (!empty($ppv->showPPVLabel)) {
$objTag->type = "warning";
$objTag->text = "PPV";
} else {
$objTag->type = "warning";
$objTag->text = __("Private");
}
} elseif (!Video::isPublic($video_id)) {
$objTag->type = "warning";
$objTag->text = __("Private");
} else {
$objTag->type = "success";
$objTag->text = $advancedCustom->paidOnlyFreeLabel;
}
}
$tags[] = $objTag;
$objTag = new stdClass();
}
/**
a = active
i = inactive
e = encoding
x = encoding error
d = downloading
u = unlisted
xmp4 = encoding mp4 error
xwebm = encoding webm error
xmp3 = encoding mp3 error
xogg = encoding ogg error
ximg = get image error
*/
if (empty($type) || $type === "status") {
$objTag = new stdClass();
$objTag->label = __("Status");
switch ($video->getStatus()) {
case 'a':
$objTag->type = "success";
$objTag->text = __("Active");
break;
case 'i':
$objTag->type = "warning";
$objTag->text = __("Inactive");
break;
case 'e':
$objTag->type = "info";
$objTag->text = __("Encoding");
break;
case 'd':
$objTag->type = "info";
$objTag->text = __("Downloading");
break;
case 'u':
$objTag->type = "info";
$objTag->text = __("Unlisted");
break;
case 'xmp4':
$objTag->type = "danger";
$objTag->text = __("Encoding mp4 error");
break;
case 'xwebm':
$objTag->type = "danger";
$objTag->text = __("Encoding xwebm error");
break;
case 'xmp3':
$objTag->type = "danger";
$objTag->text = __("Encoding xmp3 error");
break;
case 'xogg':
$objTag->type = "danger";
$objTag->text = __("Encoding xogg error");
break;
case 'ximg':
$objTag->type = "danger";
$objTag->text = __("Get imgage error");
break;
default:
$objTag->type = "danger";
$objTag->text = __("Status not found");
break;
}
$objTag->text = $objTag->text;
$tags[] = $objTag;
$objTag = new stdClass();
}
if (empty($type) || $type === "userGroups") {
$groups = UserGroups::getVideoGroups($video_id);
$objTag = new stdClass();
$objTag->label = __("Group");
if (empty($groups)) {
$status = $video->getStatus();
if ($status == 'u') {
$objTag->type = "info";
$objTag->text = __("Unlisted");
$tags[] = $objTag;
$objTag = new stdClass();
} else {
//$objTag->type = "success";
//$objTag->text = __("Public");
}
} else {
foreach ($groups as $value) {
$objTag = new stdClass();
$objTag->label = __("Group");
$objTag->type = "info";
$objTag->text = "{$value['group_name']}";
$tags[] = $objTag;
$objTag = new stdClass();
}
}
}
if (empty($type) || $type === "category") {
require_once 'category.php';
$sort = null;
if (!empty($_POST['sort']['title'])) {
$sort = $_POST['sort'];
unset($_POST['sort']);
}
$category = Category::getCategory($video->getCategories_id());
if (!empty($sort)) {
$_POST['sort'] = $sort;
}
$objTag = new stdClass();
$objTag->label = __("Category");
if (!empty($category)) {
$objTag->type = "default";
$objTag->text = $category['name'];
$tags[] = $objTag;
$objTag = new stdClass();
}
}
if (empty($type) || $type === "source") {
$url = $video->getVideoDownloadedLink();
$parse = parse_url($url);
$objTag = new stdClass();
$objTag->label = __("Source");
if (!empty($parse['host'])) {
$objTag->type = "danger";
$objTag->text = $parse['host'];
$tags[] = $objTag;
$objTag = new stdClass();
} else {
$objTag->type = "info";
$objTag->text = __("Local File");
$tags[] = $objTag;
$objTag = new stdClass();
}
}
$array2 = AVideoPlugin::getVideoTags($video_id);
if (is_array($array2)) {
$tags = array_merge($tags, $array2);
}
//var_dump($tags);
$_REQUEST['current'] = $currentPage;
$_REQUEST['rowCount'] = $rowCount;
return $tags;
}
public static function deleteTagsAsync($video_id)
{
global $global;
if (empty($video_id)) {
return false;
}
$name = "getVideoTags{$video_id}";
ObjectYPT::deleteCache($name);
_session_start();
unset($_SESSION['getVideoTags'][$video_id]);
$path = getCacheDir() . "getTagsAsync/";
if (!is_dir($path)) {
return false;
}
$cacheFileName = "{$path}_{$video_id}_";
$files = glob("{$cacheFileName}*");
foreach ($files as $file) {
unlink($file);
}
}
public static function getTagsAsync($video_id, $type = "video")
{
global $global, $advancedCustom;
$path = getCacheDir() . "getTagsAsync/";
make_path($path);
$cacheFileName = "{$path}_{$video_id}_{$type}";
$return = array();
if (!file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getTags_($video_id, $type);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > 300) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getTags.php' '$video_id' '$type' '{$cacheFileName}'");
//_error_log("getTags: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return (array) $return;
}
public function getCategories_id()
{
return $this->categories_id;
}
public function getType()
{
return $this->type;
}
public static function fixCleanTitle($clean_title, $count, $videoId, $original_title = "")
{
global $global;
if (empty($original_title)) {
$original_title = $clean_title;
}
$sql = "SELECT * FROM videos WHERE clean_title = '{$clean_title}' ";
if (!empty($videoId)) {
$sql .= " AND id != {$videoId} ";
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$cleanTitleExists = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($cleanTitleExists != false) {
return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $videoId, $original_title);
}
return $clean_title;
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function isOwner($videos_id, $users_id = 0)
{
global $global;
if (empty($users_id)) {
$users_id = User::getId();
if (empty($users_id)) {
return false;
}
}
$video_owner = self::getOwner($videos_id);
if ($video_owner) {
if ($video_owner == $users_id) {
return true;
}
}
return false;
}
public static function isOwnerFromCleanTitle($clean_title, $users_id = 0)
{
global $global;
$video = self::getVideoFromCleanTitle($clean_title);
return self::isOwner($video['id'], $users_id);
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function getOwner($videos_id)
{
global $global;
$sql = "SELECT users_id FROM videos WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
if ($videoRow != false) {
return $videoRow['users_id'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
/**
*
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function canEdit($videos_id, $users_id = 0)
{
if (empty($videos_id)) {
return false;
}
if (empty($users_id)) {
$users_id = User::getId();
if (empty($users_id)) {
return false;
}
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
if ($user->getIsAdmin()) {
return true;
}
if (Permissions::canAdminVideos()) {
return true;
}
return self::isOwner($videos_id, $users_id);
}
public static function getRandom($excludeVideoId = false)
{
return static::getVideo("", "viewable", false, $excludeVideoId);
}
public static function getVideoQueryFileter()
{
global $global;
$sql = "";
if (!empty($_GET['playlist_id'])) {
require_once $global['systemRootPath'] . 'objects/playlist.php';
$ids = PlayList::getVideosIdFromPlaylist($_GET['playlist_id']);
if (!empty($ids)) {
$sql .= " AND v.id IN (" . implode(",", $ids) . ") ";
}
}
return $sql;
}
public function getTitle()
{
return $this->title;
}
public function getClean_title()
{
return $this->clean_title;
}
public function getDescription()
{
return $this->description;
}
public function getExistingVideoFile()
{
$source = self::getHigestResolutionVideoMP4Source($this->getFilename(), true);
$size = filesize($source['path']);
if ($size <= 20) {// it is a dummy file
$url = $source['url'];
$filename = getTmpDir("getExistingVideoFile") . md5($url);
wget($url, $filename);
return $filename;
}
return $source['path'];
}
public function getTrailer1()
{
return $this->trailer1;
}
public function getTrailer2()
{
return $this->trailer2;
}
public function getTrailer3()
{
return $this->trailer3;
}
public function getRate()
{
return $this->rate;
}
public function setTrailer1($trailer1)
{
if (filter_var($trailer1, FILTER_VALIDATE_URL)) {
$this->trailer1 = $trailer1;
} else {
$this->trailer1 = "";
}
}
public function setTrailer2($trailer2)
{
if (filter_var($trailer2, FILTER_VALIDATE_URL)) {
$this->trailer2 = $trailer2;
} else {
$this->trailer2 = "";
}
}
public function setTrailer3($trailer3)
{
if (filter_var($trailer3, FILTER_VALIDATE_URL)) {
$this->trailer3 = $trailer3;
} else {
$this->trailer3 = "";
}
}
public function setRate($rate)
{
$this->rate = floatval($rate);
}
public function getYoutubeId()
{
return $this->youtubeId;
}
public function setYoutubeId($youtubeId)
{
$this->youtubeId = $youtubeId;
}
public function setTitle($title)
{
if ($title === "Video automatically booked" && !empty($this->title)) {
return false;
}
$this->title = strip_tags($title);
if (strlen($this->title) > 190) {
$this->title = substr($this->title, 0, 187) . '...';
}
}
public function setFilename($filename, $force = false)
{
if ($force || empty($this->filename)) {
$this->filename = $filename;
}
return $this->filename;
}
public function getNext_videos_id()
{
return $this->next_videos_id;
}
public function setNext_videos_id($next_videos_id)
{
$this->next_videos_id = $next_videos_id;
}
public function queue($types = array())
{
global $config;
if (!User::canUpload()) {
return false;
}
global $global;
$obj = new stdClass();
$obj->error = true;
$target = $config->getEncoderURL() . "queue";
$postFields = array(
'user' => User::getUserName(),
'pass' => User::getUserPass(),
'fileURI' => $global['webSiteRootURL'] . "videos/original_{$this->getFilename()}",
'filename' => $this->getFilename(),
'videos_id' => $this->getId(),
"notifyURL" => "{$global['webSiteRootURL']}"
);
if (empty($types) && AVideoPlugin::isEnabledByName("VideoHLS")) {
$postFields['inputHLS'] = 1;
} elseif (!empty($types)) {
foreach ($types as $key => $value) {
$postFields[$key] = $value;
}
}
_error_log("SEND To QUEUE: ($target) " . json_encode($postFields));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$r = curl_exec($curl);
$obj->response = $r;
if ($errno = curl_errno($curl)) {
$error_message = curl_strerror($errno);
//echo "cURL error ({$errno}):\n {$error_message}";
$obj->msg = "cURL error ({$errno}):\n {$error_message}";
} else {
$obj->error = false;
}
_error_log("QUEUE CURL: ($target) " . json_encode($obj));
curl_close($curl);
return $obj;
}
public function getVideoLink()
{
return $this->videoLink;
}
public function setVideoLink($videoLink)
{
$this->videoLink = $videoLink;
}
public function getCan_download()
{
return $this->can_download;
}
public function getCan_share()
{
return $this->can_share;
}
public function setCan_download($can_download)
{
$this->can_download = (empty($can_download) || $can_download === "false") ? 0 : 1;
}
public function setCan_share($can_share)
{
$this->can_share = (empty($can_share) || $can_share === "false") ? 0 : 1;
}
public function getOnly_for_paid()
{
return $this->only_for_paid;
}
public function setOnly_for_paid($only_for_paid)
{
$this->only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1;
}
/**
*
* @param type $filename
* @param type $type
* @return type .jpg .gif .webp _thumbs.jpg _Low.mp4 _SD.mp4 _HD.mp4
*/
public static function getSourceFile($filename, $type = ".jpg", $includeS3 = false)
{
global $global, $advancedCustom, $videosPaths, $VideoGetSourceFile;
//if(!isValidFormats($type)){
//return array();
//}
$cacheName = md5($filename . $type . $includeS3);
if (isset($VideoGetSourceFile[$cacheName])) {
if (!preg_match("/token=/", $VideoGetSourceFile[$cacheName]['url'])) {
return $VideoGetSourceFile[$cacheName];
}
}
// check if there is a webp image
if ($type === '.gif' && (empty($_SERVER['HTTP_USER_AGENT']) || get_browser_name($_SERVER['HTTP_USER_AGENT']) !== 'Safari')) {
$path = self::getStoragePath()."{$filename}.webp";
if (file_exists($path)) {
$type = ".webp";
}
}
if (empty($videosPaths[$filename][$type][intval($includeS3)])) {
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
$ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage');
if (!empty($aws_s3)) {
$aws_s3_obj = $aws_s3->getDataObject();
if (!empty($aws_s3_obj->useS3DirectLink)) {
$includeS3 = true;
}
} elseif (!empty($bb_b2)) {
$bb_b2_obj = $bb_b2->getDataObject();
if (!empty($bb_b2_obj->useDirectLink)) {
$includeS3 = true;
}
} elseif (!empty($ftp)) {
$includeS3 = true;
}
$token = "";
$secure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory');
if ((preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip")) {
$vars = array();
if (!empty($secure)) {
$vars[] = $secure->getToken($filename);
}
if (!empty($vars)) {
$token = "?" . implode("&", $vars);
}
}
$source = array();
$source['path'] = self::getStoragePath()."{$filename}{$type}";
if ($type == ".m3u8") {
$source['path'] = self::getStoragePath()."{$filename}/index{$type}";
}
$cleanFileName = self::getCleanFilenameFromFile($filename);
$video = Video::getVideoFromFileNameLight($cleanFileName);
if (empty($video)) {
_error_log("Video::getSourceFile($filename, $type, $includeS3) ERROR video not found ($cleanFileName)");
$VideoGetSourceFile[$cacheName] = false;
return false;
}
$canUseCDN = canUseCDN($video['id']);
if (!empty($video['sites_id']) && (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip") && @filesize($source['path']) < 20) {
$site = new Sites($video['sites_id']);
$siteURL = rtrim($site->getUrl(), '/') . '/';
$source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}";
}
} elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) {
$advancedCustom->videosCDN = rtrim($advancedCustom->videosCDN, '/') . '/';
$source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}";
}
} else {
$source['url'] = "{$global['webSiteRootURL']}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}";
}
}
/* need it because getDurationFromFile */
if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) {
if (file_exists($source['path']) && filesize($source['path']) < 1024) {
if (!empty($aws_s3)) {
$source = $aws_s3->getAddress("{$filename}{$type}");
} elseif (!empty($bb_b2)) {
$source = $bb_b2->getAddress("{$filename}{$type}");
} elseif (!empty($ftp)) {
$source = $ftp->getAddress("{$filename}{$type}");
}
}
}
if (!file_exists($source['path']) || ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10))) {
if ($type != "_thumbsV2.jpg" && $type != "_thumbsSmallV2.jpg" && $type != "_portrait_thumbsV2.jpg" && $type != "_portrait_thumbsSmallV2.jpg") {
$VideoGetSourceFile[$cacheName] = array('path' => false, 'url' => false);
return $VideoGetSourceFile[$cacheName];
}
}
$videosPaths[$filename][$type][intval($includeS3)] = $source;
} else {
$source = $videosPaths[$filename][$type][intval($includeS3)];
}
if (substr($type, -4) === ".jpg" || substr($type, -4) === ".png" || substr($type, -4) === ".gif" || substr($type, -4) === ".webp") {
$x = uniqid();
if (file_exists($source['path'])) {
$x = filemtime($source['path']);
} elseif (!empty($video)) {
$x = strtotime($video['modified']);
}
$source['url'] .= "?{$x}";
}
//ObjectYPT::setCache($name, $source);
$VideoGetSourceFile[$cacheName] = $source;
return $VideoGetSourceFile[$cacheName];
}
public static function getCleanFilenameFromFile($filename)
{
if (empty($filename)) {
return "";
}
$cleanName = str_replace(
array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku',
'_2160', '_1440', '_1080', '_720', '_480', '_360', '_240', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2'),
array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
$filename
);
$path_parts = pathinfo($cleanName);
if (!empty($path_parts["extension"]) && $path_parts["extension"] === "m3u8") {
preg_match('/videos\/([^\/]+)/', $path_parts["dirname"], $matches);
if (!empty($matches[1])) {
$path_parts['filename'] = $matches[1];
}
}
if (empty($path_parts['extension'])) {
//_error_log("Video::getCleanFilenameFromFile could not find extension of ".$filename);
if (!empty($path_parts['filename'])) {
return $path_parts['filename'];
} else {
return $filename;
}
} elseif (strlen($path_parts['extension']) > 4) {
return $cleanName;
} else {
return $path_parts['filename'];
}
}
public static function getSpecificResolution($filename, $desired_resolution)
{
$filename = self::getCleanFilenameFromFile($filename);
$cacheName = "getSpecificResolution($filename)";
$return = ObjectYPT::getCache($cacheName, 0);
if (!empty($return)) {
return object_to_array($return);
}
$name0 = "Video:::getSpecificResolution($filename)";
TimeLogStart($name0);
$name1 = "Video:::getSpecificResolution::getVideosURL_V2($filename)";
TimeLogStart($name1);
$sources = getVideosURL_V2($filename);
if (!is_array($sources)) {
_error_log("Video:::getSpecificResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources));
return array();
}
TimeLogEnd($name1, __LINE__);
$return = array();
foreach ($sources as $key => $value) {
if ($value['type'] === 'video') {
$parts = explode("_", $key);
$resolution = intval(@$parts[1]);
if (empty($resolution)) {
$name2 = "Video:::getSpecificResolution::getResolution({$value["path"]})";
TimeLogStart($name2);
$resolution = self::getResolution($value["path"]);
TimeLogEnd($name2, __LINE__);
}
if (!isset($return['resolution']) || $resolution == $desired_resolution) {
$return = $value;
$return['resolution'] = $resolution;
$return['resolution_text'] = getResolutionText($return['resolution']);
$return['resolution_label'] = getResolutionLabel($return['resolution']);
$return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}");
}
}
}
TimeLogEnd($name0, __LINE__);
ObjectYPT::setCache($cacheName, $return);
return $return;
}
public static function getHigestResolution($filename)
{
$filename = self::getCleanFilenameFromFile($filename);
$cacheName = "getHigestResolution($filename)";
$return = ObjectYPT::getCache($cacheName, 0);
if (!empty($return)) {
return object_to_array($return);
}
$name0 = "Video:::getHigestResolution($filename)";
TimeLogStart($name0);
$name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)";
TimeLogStart($name1);
$sources = getVideosURL_V2($filename);
if (!is_array($sources)) {
_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources));
return array();
}
TimeLogEnd($name1, __LINE__);
$return = array();
foreach ($sources as $key => $value) {
if ($value['type'] === 'video') {
$parts = explode("_", $key);
$resolution = intval(@$parts[1]);
if (empty($resolution)) {
$name2 = "Video:::getHigestResolution::getResolution({$value["path"]})";
TimeLogStart($name2);
- $resolution = self::getResolution($value["path"]);
+ $resolution = self::getResolutionFromFilename($value["path"]); // this is faster
+ if($resolution){
+ $resolution = self::getResolution($value["path"]);
+ }
TimeLogEnd($name2, __LINE__);
}
if (!isset($return['resolution']) || $resolution > $return['resolution']) {
$return = $value;
$return['resolution'] = $resolution;
$return['resolution_text'] = getResolutionText($return['resolution']);
$return['resolution_label'] = getResolutionLabel($return['resolution']);
$return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}");
}
}
}
TimeLogEnd($name0, __LINE__);
ObjectYPT::setCache($cacheName, $return);
return $return;
}
public static function getResolutionFromFilename($filename)
{
$resolution = false;
if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) {
if (!empty($matches[1])) {
$resolution = intval($matches[1]);
}
} elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) {
if (!empty($matches[1])) {
$resolution = intval($matches[1]);
}
}
//var_dump($filename, $resolution);exit;
return $resolution;
}
public static function getHigestResolutionVideoMP4Source($filename, $includeS3 = false)
{
$types = array('', '_HD', '_SD', '_Low');
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".mp4", $includeS3);
if (!empty($source['url'])) {
return $source;
}
}
return false;
}
public static function getHigherVideoPathFromID($videos_id)
{
if (empty($videos_id)) {
return false;
}
$paths = self::getVideosPathsFromID($videos_id);
$types = array(0, 2160, 1330, 1080, 720, 'HD', 'SD', 'Low', 480, 360, 240);
if (!empty($paths['mp4'])) {
foreach ($types as $value) {
if (!empty($paths['mp4'][$value])) {
if (is_string($paths['mp4'][$value])) {
return $paths['mp4'][$value];
} else {
return $paths['mp4'][$value]["url"];
}
}
}
}
if (!empty($paths['webm'])) {
foreach ($types as $value) {
if (!empty($paths['webm'][$value])) {
if (is_string($paths['webm'][$value])) {
return $paths['webm'][$value];
} else {
return $paths['webm'][$value]["url"];
}
}
}
}
if (!empty($paths['m3u8'])) {
if (!empty($paths['m3u8'])) {
if (is_string($paths['m3u8']["url"])) {
return $paths['m3u8']["url"];
} elseif (is_string($paths['m3u8'][$value])) {
return $paths['m3u8'][$value];
} else {
return $paths['m3u8'][$value]["url"];
}
}
}
if (!empty($paths['mp3'])) {
return $paths['mp3'];
}
return false;
}
public static function getVideosPathsFromID($videos_id)
{
if (empty($videos_id)) {
return false;
}
$video = new Video("", "", $videos_id);
return self::getVideosPaths($video->getFilename(), true);
}
public static function getVideosPaths($filename, $includeS3 = false)
{
$types = array('', '_Low', '_SD', '_HD', '_2160', '_1440', '_1080', '_720', '_480', '_360', '_240');
$videos = array();
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (!empty($plugin)) {
$videos = VideoHLS::getSourceFile($filename, $includeS3);
}
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".mp4", $includeS3);
if (!empty($source['url'])) {
$videos['mp4'][str_replace("_", "", $value)] = $source['url'];
}
}
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".webm", $includeS3);
if (!empty($source['url'])) {
$videos['webm'][str_replace("_", "", $value)] = $source['url'];
}
}
$source = self::getSourceFile($filename, ".pdf", $includeS3);
if (!empty($source['url'])) {
$videos['pdf'] = $source['url'];
}
$source = self::getSourceFile($filename, ".zip", $includeS3);
if (!empty($source['url'])) {
$videos['zip'] = $source['url'];
}
$source = self::getSourceFile($filename, ".mp3", $includeS3);
if (!empty($source['url'])) {
$videos['mp3'] = $source['url'];
}
return $videos;
}
public static function getStoragePath(){
global $global;
$path = "{$global['systemRootPath']}videos/";
return $path;
}
public static function getStoragePathFromFileName($filename){
$cleanFileName = self::getCleanFilenameFromFile($filename);
$path = self::getStoragePath()."{$cleanFileName}/";
make_path($path);
return $path;
}
public static function getStoragePathFromVideosId($videos_id){
$v = new Video("", "", $videos_id);
return self::getStoragePathFromFileName($v->getFilename());
}
public static function getImageFromFilename($filename, $type = "video", $async = false)
{
global $advancedCustom;
// I dont know why but I had to remove it to avoid ERR_RESPONSE_HEADERS_TOO_BIG
header_remove('Set-Cookie');
if (empty($advancedCustom->AsyncJobs) && !$async) {
return self::getImageFromFilename_($filename, $type);
} else {
return self::getImageFromFilenameAsync($filename, $type);
}
}
public static function getPoster($videos_id)
{
$images = self::getImageFromID($videos_id);
if (!empty($images->poster)) {
return $images->poster;
}
if (!empty($images->posterPortrait)) {
return $images->poster;
}
return false;
}
public static function getRokuImage($videos_id)
{
global $global;
$images = self::getImageFromID($videos_id);
$imagePath = $images->posterLandscapePath;
if (empty($imagePath) || !file_exists($imagePath)) {
$imagePath = $images->posterLandscapeThumbs;
}
if (empty($imagePath) || !file_exists($imagePath)) {
$imagePath = $images->poster;
}
$rokuImage = str_replace(".jpg", "_roku.jpg", $imagePath);
if (convertImageToRoku($images->posterLandscapePath, $rokuImage)) {
return str_replace($global['systemRootPath'], $global['webSiteRootURL'], $rokuImage);
}
return "{$global['webSiteRootURL']}view/img/notfound.jpg";
}
public static function clearImageCache($filename, $type = "video")
{
$cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : "");
return ObjectYPT::deleteCache($cacheFileName);
}
public static function getImageFromFilename_($filename, $type = "video")
{
if (empty($filename)) {
return array();
}
global $_getImageFromFilename_;
if (empty($_getImageFromFilename_)) {
$_getImageFromFilename_ = array();
}
$cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : "");
if (!empty($_getImageFromFilename_[$cacheFileName])) {
$obj = $_getImageFromFilename_[$cacheFileName];
} else {
$cache = ObjectYPT::getCache($cacheFileName, 0);
if (!empty($cache)) {
return $cache;
}
global $global, $advancedCustom;
/*
$name = "getImageFromFilename_{$filename}{$type}_";
$cached = ObjectYPT::getCache($name, 86400);//one day
if(!empty($cached)){
return $cached;
}
*
*/
$obj = new stdClass();
$gifSource = self::getSourceFile($filename, ".gif");
$gifPortraitSource = self::getSourceFile($filename, "_portrait.gif");
$jpegSource = self::getSourceFile($filename, ".jpg");
$jpegPortraitSource = self::getSourceFile($filename, "_portrait.jpg");
$jpegPortraitThumbs = self::getSourceFile($filename, "_portrait_thumbsV2.jpg");
$jpegPortraitThumbsSmall = self::getSourceFile($filename, "_portrait_thumbsSmallV2.jpg");
$thumbsSource = self::getSourceFile($filename, "_thumbsV2.jpg");
$thumbsSmallSource = self::getSourceFile($filename, "_thumbsSmallV2.jpg");
if (empty($jpegSource)) {
return array();
}
$obj->poster = $jpegSource['url'];
$obj->posterPortrait = $jpegPortraitSource['url'];
$obj->posterPortraitPath = $jpegPortraitSource['path'];
$obj->posterPortraitThumbs = $jpegPortraitThumbs['url'];
$obj->posterPortraitThumbsSmall = $jpegPortraitThumbsSmall['url'];
$obj->thumbsGif = $gifSource['url'];
$obj->gifPortrait = $gifPortraitSource['url'];
$obj->thumbsJpg = $thumbsSource['url'];
$obj->thumbsJpgSmall = $thumbsSmallSource['url'];
$obj->posterLandscape = $jpegSource['url'];
$obj->posterLandscapePath = $jpegSource['path'];
$obj->posterLandscapeThumbs = $thumbsSource['url'];
$obj->posterLandscapeThumbsSmall = $thumbsSmallSource['url'];
if (file_exists($gifSource['path'])) {
$obj->thumbsGif = $gifSource['url'];
}
if (file_exists($jpegPortraitSource['path'])) {
// create thumbs
if (!file_exists($jpegPortraitThumbs['path']) && filesize($jpegPortraitSource['path']) > 1024) {
_error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbs['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
} else {
im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
}
}
// create thumbs
if (!file_exists($jpegPortraitThumbsSmall['path']) && filesize($jpegPortraitSource['path']) > 1024) {
_error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbsSmall['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
} else {
im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait, 5);
}
}
} else {
if ($type == "article") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/article_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/article_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/article_portrait.png";
} elseif ($type == "pdf") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
} /* else if ($type == "image") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/image_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/image_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/image_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/image_portrait.png";
} */ elseif ($type == "zip") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/zip_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
} else {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
}
}
if (file_exists($jpegSource['path'])) {
$obj->poster = $jpegSource['url'];
$obj->thumbsJpg = $thumbsSource['url'];
// create thumbs
if (!file_exists($thumbsSource['path']) && filesize($jpegSource['path']) > 1024) {
_error_log("Resize JPG {$jpegSource['path']}, {$thumbsSource['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
} else {
im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
}
}
// create thumbs
if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) {
_error_log("Resize Small JPG {$jpegSource['path']}, {$thumbsSmallSource['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
} else {
im_resizeV2($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape, 5);
}
}
} else {
if ($type == "article") {
$obj->poster = "{$global['webSiteRootURL']}view/img/article.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/article.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/article.png";
} elseif ($type == "pdf") {
$obj->poster = "{$global['webSiteRootURL']}view/img/pdf.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/pdf.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/pdf.png";
} elseif ($type == "image") {
$obj->poster = "{$global['webSiteRootURL']}view/img/image.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/image.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/image.png";
} elseif ($type == "zip") {
$obj->poster = "{$global['webSiteRootURL']}view/img/zip.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/zip.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/zip.png";
} elseif (($type !== "audio") && ($type !== "linkAudio")) {
$obj->poster = "{$global['webSiteRootURL']}view/img/notfound.jpg";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/notfoundThumbs.jpg";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/notfoundThumbsSmall.jpg";
} else {
$obj->poster = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/audio_waveThumbs.jpg";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/audio_waveThumbsSmall.jpg";
}
}
if (empty($obj->thumbsJpg)) {
$obj->thumbsJpg = $obj->poster;
}
if (empty($obj->thumbsJpgSmall)) {
$obj->thumbsJpgSmall = $obj->poster;
}
//ObjectYPT::setCache($name, $obj);
if (!empty($advancedCustom->disableAnimatedGif)) {
$obj->thumbsGif = false;
}
ObjectYPT::setCache($cacheFileName, $obj);
$_getImageFromFilename_[$cacheFileName] = $obj;
}
return $obj;
}
public static function getImageFromFilenameAsync($filename, $type = "video")
{
global $global, $advancedCustom;
$return = array();
$path = getCacheDir() . "getImageFromFilenameAsync/";
make_path($path);
$cacheFileName = "{$path}_{$filename}_{$type}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getImageFromFilename_($filename, $type);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getImageFromFilenameAsync.php' '$filename' '$type' '{$cacheFileName}'");
//_error_log("getImageFromFilenameAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return $return;
}
public static function getImageFromID($videos_id, $type = "video")
{
$video = new Video("", "", $videos_id);
return self::getImageFromFilename($video->getFilename());
}
public function getViews_count()
{
return intval($this->views_count);
}
public static function get_clean_title($videos_id)
{
global $global;
$sql = "SELECT * FROM videos WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
if ($videoRow != false) {
return $videoRow['clean_title'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
public static function get_id_from_clean_title($clean_title)
{
global $global;
$sql = "SELECT * FROM videos WHERE clean_title = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($clean_title));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
if ($videoRow != false) {
return $videoRow['id'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
public function getChannelName()
{
return User::_getChannelName($this->getUsers_id());
}
public function getChannelLink()
{
return User::getChannelLink($this->getUsers_id());
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $clean_title
* @param type $embed
* @param type $type URLFriendly or permalink
* @return String a web link
*/
public static function getLinkToVideo($videos_id, $clean_title = "", $embed = false, $type = "URLFriendly", $get = array())
{
if (!empty($_GET['evideo'])) {
$v = self::decodeEvideo();
if (!empty($v['video']['videoLink'])) {
if ($embed) {
return parseVideos($v['video']['videoLink']);
} else {
return $v['video']['videoLink'];
}
}
}
global $global, $advancedCustomUser, $advancedCustom;
if (empty($videos_id) && !empty($clean_title)) {
$videos_id = self::get_id_from_clean_title($clean_title);
}
$video = new Video("", "", $videos_id);
if ($advancedCustomUser->addChannelNameOnLinks) {
$get['channelName'] = $video->getChannelName();
}
unset($get['v']);
unset($get['videoName']);
unset($get['videoName']);
unset($get['isMediaPlaySite']);
unset($get['parentsOnly']);
$get_http = http_build_query($get);
if (empty($get_http)) {
$get_http = "";
} else {
$get_http = "?{$get_http}";
}
if ($type == "URLFriendly") {
$cat = "";
if (!empty($_GET['catName'])) {
$cat = "cat/{$_GET['catName']}/";
}
if (empty($clean_title)) {
$clean_title = $video->getClean_title();
}
$clean_title = urlencode($clean_title);
$subDir = "video";
$subEmbedDir = "videoEmbed";
if ($video->getType() == 'article') {
$subDir = "article";
$subEmbedDir = "articleEmbed";
}
if ($embed) {
if (empty($advancedCustom->useVideoIDOnSEOLinks)) {
return "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}";
} else {
return "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}";
}
} else {
if (empty($advancedCustom->useVideoIDOnSEOLinks)) {
return "{$global['webSiteRootURL']}{$cat}{$subDir}/{$clean_title}{$get_http}";
} else {
return "{$global['webSiteRootURL']}{$subDir}/{$videos_id}/{$clean_title}{$get_http}";
}
}
} else {
if ($embed) {
return "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}";
} else {
return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}";
}
}
}
public static function getPermaLink($videos_id, $embed = false, $get = array())
{
return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get);
}
public static function getURLFriendly($videos_id, $embed = false, $get = array())
{
return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get);
}
public static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = array())
{
return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get);
}
public static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = array())
{
return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get);
}
public static function getLink($videos_id, $clean_title, $embed = false, $get = array())
{
global $advancedCustom;
if (!empty($advancedCustom->usePermalinks)) {
$type = "permalink";
} else {
$type = "URLFriendly";
}
return self::getLinkToVideo($videos_id, $clean_title, $embed, $type, $get);
}
public static function getTotalVideosThumbsUpFromUser($users_id, $startDate, $endDate)
{
global $global;
$sql = "SELECT id from videos WHERE users_id = ? ";
$res = sqlDAL::readSql($sql, "i", array($users_id));
$videoRows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = array('thumbsUp' => 0, 'thumbsDown' => 0);
if ($res != false) {
foreach ($videoRows as $row) {
$values = array($row['id']);
$format = "i";
$sql = "SELECT id from likes WHERE videos_id = ? AND `like` = 1 ";
if (!empty($startDate)) {
$sql .= " AND `created` >= ? ";
$format .= "s";
$values[] = $startDate;
}
if (!empty($endDate)) {
$sql .= " AND `created` <= ? ";
$format .= "s";
$values[] = $endDate;
}
$res = sqlDAL::readSql($sql, $format, $values);
$countRow = sqlDAL::num_rows($res);
sqlDAL::close($res);
$r['thumbsUp'] += $countRow;
$format = "";
$values = array();
$sql = "SELECT id from likes WHERE videos_id = {$row['id']} AND `like` = -1 ";
if (!empty($startDate)) {
$sql .= " AND `created` >= ? ";
$format .= "s";
$values[] = $startDate;
}
if (!empty($endDate)) {
$sql .= " AND `created` <= ? ";
$format .= "s";
$values[] = $endDate;
}
$res = sqlDAL::readSql($sql, $format, $values);
$countRow = sqlDAL::num_rows($res);
sqlDAL::close($res);
$r['thumbsDown'] += $countRow;
}
}
return $r;
}
public static function deleteThumbs($filename, $doNotDeleteSprit = false)
{
if (empty($filename)) {
return false;
}
global $global;
$filePath = Video::getStoragePath()."{$filename}";
// Streamlined for less coding space.
$files = glob("{$filePath}*_thumbs*.jpg");
foreach ($files as $file) {
if (file_exists($file)) {
if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) {
continue;
}
@unlink($file);
}
}
ObjectYPT::deleteCache($filename);
ObjectYPT::deleteCache($filename . "article");
ObjectYPT::deleteCache($filename . "pdf");
ObjectYPT::deleteCache($filename . "video");
Video::clearImageCache($filename);
Video::clearImageCache($filename, "article");
Video::clearImageCache($filename, "pdf");
Video::clearImageCache($filename, "audio");
clearVideosURL($filename);
return true;
}
public static function clearCache($videos_id)
{
_error_log("Video:clearCache($videos_id)");
$video = new Video("", "", $videos_id);
$filename = $video->getFilename();
if (empty($filename)) {
_error_log("Video:clearCache filename not found");
return false;
}
self::deleteThumbs($filename, true);
ObjectYPT::deleteCache("otherInfo{$videos_id}");
ObjectYPT::deleteCache($filename);
ObjectYPT::deleteCache("getVideosURL_V2$filename");
ObjectYPT::deleteCache($filename . "article");
ObjectYPT::deleteCache($filename . "pdf");
ObjectYPT::deleteCache($filename . "video");
Video::clearImageCache($filename);
Video::clearImageCache($filename, "article");
Video::clearImageCache($filename, "pdf");
Video::clearImageCache($filename, "audio");
Video::deleteTagsAsync($videos_id);
clearVideosURL($filename);
AVideoPlugin::deleteVideoTags($videos_id);
ObjectYPT::setLastDeleteALLCacheTime();
return true;
}
public static function clearCacheFromFilename($fileName)
{
_error_log("Video:clearCacheFromFilename($fileName)");
$video = self::getVideoFromFileNameLight($fileName);
if (empty($video['id'])) {
return false;
}
return self::clearCache($video['id']);
}
public static function getVideoPogress($videos_id, $users_id = 0)
{
if (empty($users_id)) {
if (!User::isLogged()) {
return 0;
}
$users_id = User::getId();
}
return VideoStatistic::getLastVideoTimeFromVideo($videos_id, $users_id);
}
public static function getVideoPogressPercent($videos_id, $users_id = 0)
{
$lastVideoTime = self::getVideoPogress($videos_id, $users_id);
if (empty($lastVideoTime)) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
// start incremental search and save
$sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$row = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (empty($row) || empty($row['duration'])) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
$duration = parseDurationToSeconds($row['duration']);
if (empty($duration)) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
if ($lastVideoTime > $duration) {
return array('percent' => 100, 'lastVideoTime' => $lastVideoTime);
}
return array('percent' => ($lastVideoTime / $duration) * 100, 'lastVideoTime' => $lastVideoTime);
}
public function getRrating()
{
return $this->rrating;
}
public function setRrating($rrating)
{
$rrating = strtolower($rrating);
if (!in_array($rrating, self::$rratingOptions)) {
$rrating = '';
}
$this->rrating = $rrating;
}
public static function getVideoType($filename)
{
global $_getVideoType;
if (!isset($_getVideoType)) {
$_getVideoType = array();
}
if (isset($_getVideoType[$filename])) {
return $_getVideoType[$filename];
}
$obj = new stdClass();
$paths = self::getVideosPaths($filename);
$obj->mp4 = !empty($paths['mp4']) ? true : false;
$obj->webm = !empty($paths['webm']) ? true : false;
$obj->m3u8 = !empty($paths['m3u8']) ? true : false;
$obj->pdf = !empty($paths['pdf']) ? true : false;
$obj->mp3 = !empty($paths['mp3']) ? true : false;
$_getVideoType[$filename] = $obj;
return $obj;
}
public static function getVideoTypeLabels($filename)
{
$obj = self::getVideoType($filename);
$labels = "";
if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) {
return 'Other ';
}
if ($obj->mp4) {
$labels .= 'MP4 ';
}
if ($obj->webm) {
$labels .= 'Webm ';
}
if ($obj->m3u8) {
$labels .= 'HLS ';
}
if ($obj->pdf) {
$labels .= 'PDF ';
}
if ($obj->mp3) {
$labels .= 'MP3 ';
}
return $labels;
}
/**
* Based on Roku Type
* @param type $filename
* @return string
*/
public static function getVideoTypeText($filename)
{
$obj = self::getVideoType($filename);
$labels = "";
if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) {
return __('Other');
}
if ($obj->mp4) {
return 'MP4';
}
if ($obj->webm) {
return 'WEBM';
}
if ($obj->m3u8) {
return 'HLS';
}
if ($obj->pdf) {
return 'PDF';
}
if ($obj->mp3) {
return 'MP3';
}
return $labels;
}
public static function isPublic($videos_id)
{
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
return true;
}
return false;
}
public static function userGroupAndVideoGroupMatch($users_id, $videos_id)
{
if (empty($videos_id)) {
return false;
}
$ppv = AVideoPlugin::loadPluginIfEnabled("PayPerView");
if ($ppv) {
$ppv->userCanWatchVideo($users_id, $videos_id);
}
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
return true;
}
if (empty($users_id)) {
return false;
}
$rowsUser = UserGroups::getUserGroups(User::getId());
if (empty($rowsUser)) {
return false;
}
foreach ($rows as $value) {
foreach ($rowsUser as $value2) {
if ($value['id'] === $value2['id']) {
return true;
}
}
}
return false;
}
public function getExternalOptions()
{
return $this->externalOptions;
}
public function setExternalOptions($externalOptions)
{
$this->externalOptions = $externalOptions;
}
public function setVideoStartSeconds($videoStartSeconds)
{
$externalOptions = json_decode($this->getExternalOptions());
$externalOptions->videoStartSeconds = $videoStartSeconds;
$this->setExternalOptions(json_encode($externalOptions));
}
public function getSerie_playlists_id()
{
return $this->serie_playlists_id;
}
public function setSerie_playlists_id($serie_playlists_id)
{
$this->serie_playlists_id = $serie_playlists_id;
}
public static function getVideoFromSeriePlayListsId($serie_playlists_id)
{
global $global, $config;
$serie_playlists_id = intval($serie_playlists_id);
$sql = "SELECT * FROM videos WHERE serie_playlists_id = '$serie_playlists_id' LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
/**
* if will show likes, comments, share, etc
* @return boolean
*/
public static function showYoutubeModeOptions()
{
global $video;
if (!empty($_GET['evideo'])) {
$v = self::decodeEvideo();
if (empty($v['video']['views_count'])) {
return false;
} else {
return true;
}
}
if (empty($video) || $video['type'] === 'notfound') {
return false;
}
return true;
}
public static function decodeEvideo()
{
$evideo = false;
if (!empty($_GET['evideo'])) {
$evideo = json_decode(decryptString($_GET['evideo']));
}
$video = array();
if (!empty($evideo)) {
$video['id'] = 0;
$video['type'] = 'embed';
$video['rotation'] = 0;
$video['videoLink'] = $evideo->videoLink;
$video['title'] = $evideo->title;
$video['clean_title'] = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\] ]+/', '-', trim(strtolower(cleanString($evideo->title))));
if (empty($evideo->description) && !empty($evideo->videos_id)) {
$divId = uniqid();
$video['description'] = '
';
} else {
$video['description'] = @$evideo->description;
}
$video['duration'] = @$evideo->duration;
$video['creator'] = @$evideo->creator;
$video['likes'] = "";
$video['dislikes'] = "";
$video['category'] = "embed";
$video['views_count'] = intval(@$evideo->views_count);
}
return array('evideo' => $evideo, 'video' => $video);
}
private function getBlockedUsersIdsArray($users_id = 0)
{
if (empty($users_id)) {
$users_id = intval(User::getId());
}
if (empty($users_id)) {
return array();
}
if (!User::isLogged()) {
return array();
}
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (empty($report)) {
return array();
}
return ReportVideo::getAllReportedUsersIdFromUser($users_id);
}
public static function getIncludeType($video)
{
$vType = $video['type'];
if ($vType == 'linkVideo') {
- $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video';
+ if(!preg_match('/m3u8/', $video['videoLink'])){
+ $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video';
+ }else{
+ $vType = 'video';
+ }
} elseif ($vType == 'live') {
$vType = '../../plugin/Live/view/liveVideo';
} elseif ($vType == 'linkAudio') {
$vType = 'audio';
}
if (!in_array($vType, Video::$typeOptions)) {
$vType = 'video';
}
return $vType;
}
private static function getFullTextSearch($columnsArray, $search, $connection = "OR"){
global $global;
$search = $global['mysqli']->real_escape_string(xss_esc($search));
if(empty($columnsArray) || empty($search)){
return "";
}
$sql = "(";
$matches = array();
foreach ($columnsArray as $value) {
$matches[] = " (MATCH({$value}) AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)) ";
}
$sql .= implode(" OR ", $matches);
$sql .= ")";
return "{$connection} {$sql}";
}
}
}
// just to convert permalink into clean_title
if (!empty($_GET['v']) && empty($_GET['videoName'])) {
$_GET['videoName'] = Video::get_clean_title($_GET['v']);
}
diff --git a/objects/videoAddViewCount.json.php b/objects/videoAddViewCount.json.php
index c98e481b1..510f32dc1 100644
--- a/objects/videoAddViewCount.json.php
+++ b/objects/videoAddViewCount.json.php
@@ -1,55 +1,58 @@
getDuration());
if (!empty($seconds)) {
$percent = (intval($_POST['currentTime']) / $seconds) * 100;
$percentOptions = array(25,50,75,100);
foreach ($percentOptions as $value) {
if ($percent >= $value) {
if (empty($_SESSION['addViewCount'][$_POST['id']][$value]) && !empty($_POST['currentTime'])) {
if ($obj->addViewPercent($value)) {
_session_start();
$_SESSION['addViewCount'][$_POST['id']][$value] = 1;
}
}
}
}
}
if (empty($_SESSION['addViewCount'][$_POST['id']]['time'])) {
$resp = $obj->addView();
_session_start();
$_SESSION['addViewCount'][$_POST['id']]['time'] = strtotime("+{$seconds} seconds");
} elseif (!empty($_POST['currentTime'])) {
$resp = VideoStatistic::updateStatistic($obj->getId(), User::getId(), intval($_POST['currentTime']));
} else {
$resp = 0;
}
$count = $obj->getViews_count();
$obj2 = new stdClass();
$obj2->status = !empty($resp);
$obj2->count = $count;
$obj2->resp = $resp;
echo json_encode($obj2);
diff --git a/plugin/AVideoPlugin.php b/plugin/AVideoPlugin.php
index da145d8db..b47fcfa41 100644
--- a/plugin/AVideoPlugin.php
+++ b/plugin/AVideoPlugin.php
@@ -1,1483 +1,1511 @@
$timeLimit) {
_error_log("The plugin [{$pluginName}] takes {$total_time} seconds to complete. URL: " . getSelfURI() . " IP: " . getRealIpAddr(), AVideoLog::$WARNING);
}
}
public static function addRoutes() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->addRoutes();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return false;
}
public static function addView($videos_id, $total) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->addView($videos_id, $total);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return false;
}
public static function getHeadCode() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getHeadCode();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getChartTabs() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
if (method_exists($p, 'getChartTabs')) {
$str .= $p->getChartTabs();
} else {
$checkStr = $p->getChartContent();
if (!empty($checkStr)) {
$str .= ' ';
}
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getChartContent() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$checkStr = $p->getChartContent();
if (!empty($checkStr)) {
$str .= '';
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getGallerySection() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getGallerySection();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getHelpToc() {
$plugins = Plugin::getAllEnabled();
$str = "" . __("Table of content") . " ";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$t = $p->getHelp();
if (!empty($t)) {
$str .= "" . __($value['name']) . " ";
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str . " ";
}
public static function getHelp() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$t = $p->getHelp();
$str .= $t;
if (!empty($t)) {
$str .= " ";
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getFooterCode() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= PHP_EOL."".PHP_EOL;
$str .= $p->getFooterCode();
$str .= PHP_EOL."".PHP_EOL;
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getJSFiles() {
$plugins = Plugin::getAllEnabled();
$allFiles = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$js = $p->getJSFiles();
if (is_array($js)) {
$allFiles = array_merge($allFiles, $js);
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $allFiles;
}
public static function getCSSFiles() {
$plugins = Plugin::getAllEnabled();
$allFiles = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$allFiles = array_merge($allFiles, $p->getCSSFiles());
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $allFiles;
}
public static function getHTMLBody() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getHTMLBody();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getHTMLMenuLeft() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getHTMLMenuLeft();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getHTMLMenuRight() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getHTMLMenuRight();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getFirstPage() {
return static::getEnabledFirstPage();
}
public static function getEnabledFirstPage() {
$plugins = Plugin::getAllEnabled();
$firstPage = false;
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (!is_object($p)) {
continue;
}
$fp = $p->getFirstPage();
if (!empty($fp)) {
$firstPage = $fp;
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $firstPage;
}
static function loadPlugin($name, $forceReload=false) {
global $global, $pluginIsLoaded;
if (empty($pluginIsLoaded)) {
$pluginIsLoaded = array();
}
$loadPluginFile = "{$global['systemRootPath']}plugin/{$name}/{$name}.php";
// need to add dechex because some times it return an negative value and make it fails on javascript playlists
if (!isset($pluginIsLoaded[$name]) && empty($forceReload)) {
$pluginIsLoaded[$name] = false;
if (file_exists($loadPluginFile)) {
require_once $loadPluginFile;
if (class_exists($name)) {
$code = "\$p = new {$name}();";
eval($code);
if (is_object($p)) {
$pluginIsLoaded[$name] = $p;
} else {
_error_log("[loadPlugin] eval failed for plugin ($name) code ($code) code result ($codeResult) included file $loadPluginFile", AVideoLog::$ERROR);
}
}
}
}
return $pluginIsLoaded[$name];
}
static function loadPluginIfEnabled($name) {
$p = static::loadPlugin($name);
if ($p) {
$uuid = $p->getUUID();
if (static::isEnabled($uuid)) {
return $p;
}
}
return false;
}
static function isPluginTablesInstalled($name, $installIt = false) {
global $global, $isPluginTablesInstalled;
$name = self::fixName($name);
$installSQLFile = "{$global['systemRootPath']}plugin/{$name}/install/install.sql";
if (isset($isPluginTablesInstalled[$installSQLFile])) {
return $isPluginTablesInstalled[$installSQLFile];
}
- _error_log("isPluginTablesInstalled: Check for {$installSQLFile}");
+ //_error_log("isPluginTablesInstalled: Check for {$installSQLFile}");
if (!file_exists($installSQLFile)) {
$isPluginTablesInstalled[$installSQLFile] = true;
return $isPluginTablesInstalled[$installSQLFile];
}
$lines = file($installSQLFile);
foreach ($lines as $line) {
$pattern1 = "/CREATE TABLE IF NOT EXISTS `?([a-z0-9_]+)[` (]?/i";
$pattern2 = "/CREATE TABLE[^`]+`?([a-z0-9_]+)[` (]?/i";
if (preg_match($pattern1, $line, $matches)) {
if (!empty($matches[1])) {
//_error_log("isPluginTablesInstalled: Found ({$matches[1]})");
if (!ObjectYPT::isTableInstalled($matches[1])) {
//_error_log("isPluginTablesInstalled: ({$matches[1]}) is NOT installed");
if ($installIt) {
sqlDAL::executeFile($installSQLFile);
return self::isPluginTablesInstalled($name);
} else {
//_error_log("isPluginTablesInstalled: You need to install table {$matches[1]} for the plugin ({$name})", AVideoLog::$ERROR);
$isPluginTablesInstalled[$installSQLFile] = false;
return $isPluginTablesInstalled[$installSQLFile];
}
}else{
//_error_log("isPluginTablesInstalled: ({$matches[1]}) is installed");
}
}
} else if (preg_match($pattern2, $line, $matches)) {
if (!empty($matches[1])) {
if (!ObjectYPT::isTableInstalled($matches[1])) {
_error_log("You need to install table {$matches[1]} for the plugin ({$name})", AVideoLog::$ERROR);
$isPluginTablesInstalled[$installSQLFile] = false;
return $isPluginTablesInstalled[$installSQLFile];
}
}
}
}
$isPluginTablesInstalled[$installSQLFile] = true;
return $isPluginTablesInstalled[$installSQLFile];
}
static function getObjectData($name) {
return self::getDataObject($name);
}
static function getDataObject($name) {
global $pluginGetDataObject;
if (!isset($pluginGetDataObject)) {
$pluginGetDataObject = array();
}
if (!empty($pluginGetDataObject[$name])) {
return $pluginGetDataObject[$name];
}
$p = static::loadPlugin($name);
if ($p) {
$pluginGetDataObject[$name] = $p->getDataObject();
return $pluginGetDataObject[$name];
}
return false;
}
static function getObjectDataIfEnabled($name) {
return self::getDataObjectIfEnabled($name);
}
static function getDataObjectIfEnabled($name) {
$p = static::loadPlugin($name);
if ($p) {
$uuid = $p->getUUID();
if (static::isEnabled($uuid)) {
return static::getObjectData($name);
}
}
return false;
}
static function xsendfilePreVideoPlay() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->xsendfilePreVideoPlay();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getVideosManagerListButton() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getVideosManagerListButton();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getVideosManagerListButtonTitle() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getVideosManagerListButtonTitle();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getUsersManagerListButton() {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getUsersManagerListButton();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getWatchActionButton($videos_id) {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getWatchActionButton($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getNetflixActionButton($videos_id) {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getNetflixActionButton($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
static function getGalleryActionButton($videos_id) {
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getGalleryActionButton($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function isEnabled($uuid) {
return !empty(Plugin::getEnabled($uuid));
}
public static function exists($name) {
global $global;
$name = self::fixName($name);
$filename = "{$global['systemRootPath']}plugin/{$name}/{$name}.php";
return file_exists($filename);
}
static function isEnabledByName($name) {
global $isPluginEnabledByName;
if (empty($isPluginEnabledByName)) {
$isPluginEnabledByName = array();
}
if (isset($isPluginEnabledByName[$name])) {
return $isPluginEnabledByName[$name];
}
$p = static::loadPluginIfEnabled($name);
$isPluginEnabledByName[$name] = !empty($p);
return $isPluginEnabledByName[$name];
}
static function getLogin() {
$plugins = Plugin::getAllEnabled();
$logins = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$l = $p->getLogin();
if (is_string($l) && file_exists($l)) { // it is a login form
$logins[] = $l;
} else if (!empty($l->type)) { // it is a hybridauth
$logins[] = array('parameters' => $l, 'loginObject' => $p);
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $logins;
}
public static function getStart() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
//self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getStart();
}
//self::YPTend("{$value['dirName']}::".__FUNCTION__);
}
}
public static function getEnd() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getEnd();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function afterVideoJS() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->afterVideoJS();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function afterNewVideo($videos_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->afterNewVideo($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function afterDonation($from_users_id, $how_much, $videos_id, $users_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->afterDonation($from_users_id, $how_much, $videos_id, $users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function afterNewComment($comments_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->afterNewComment($comments_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function afterNewResponse($comments_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->afterNewResponse($comments_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getChannelButton() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getChannelButton();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getVideoManagerButton() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getVideoManagerButton();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getLivePanel() {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getLivePanel();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getModeYouTube($videos_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getModeYouTube($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getModeYouTubeLive($users_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getModeYouTubeLive($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getEmbed($videos_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getEmbed($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getChannel($user_id, $user) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->getChannel($user_id, $user);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function getLiveApplicationArray() {
$plugins = Plugin::getAllEnabled();
$array = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$appArray = $p->getLiveApplicationArray();
$array = array_merge($array, $appArray);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $array;
}
public static function getPlayListButtons($playlist_id = "") {
if (empty($playlist_id))
return "";
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getPlayListButtons($playlist_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getMyAccount($users_id = "") {
if (empty($users_id))
return "";
$plugins = Plugin::getAllEnabled();
$str = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$str .= $p->getMyAccount($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $str;
}
public static function getPluginUserOptions() {
$plugins = Plugin::getAllEnabled();
$userOptions = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$userOptions = array_merge($userOptions, $p->getUserOptions());
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $userOptions;
}
/**
*
* @return type return a list of IDs of the user groups
*/
public static function getDynamicUserGroupsId($users_id) {
$plugins = Plugin::getAllEnabled();
$array = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$appArray = $p->getDynamicUserGroupsId($users_id);
$array = array_merge($array, $appArray);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $array;
}
public static function getUserOptions() {
$userOptions = static::getPluginUserOptions();
$str = "";
foreach ($userOptions as $userOption => $id) {
$str .= "
" . __($userOption) .
"
";
}
return $str;
}
public static function addUserBtnJS() {
$userOptions = static::getPluginUserOptions();
$userOptions = array();
$js = "";
foreach ($userOptions as $userOption => $id) {
$js .= " $('#$id').prop('checked', false);\n";
}
return $js;
}
public static function updateUserFormJS() {
$userOptions = static::getPluginUserOptions();
$js = "";
foreach ($userOptions as $userOption => $id) {
$js .= " \"$id\": $('#$id').is(':checked'),\n";
}
return $js;
}
public static function loadUsersFormJS() {
$userOptions = static::getPluginUserOptions();
$js = "";
foreach ($userOptions as $userOption => $id) {
$js .= " $('#$id').prop('checked', (row.$id == \"1\" ? true : false));
\n";
}
return $js;
}
public static function navBarButtons() {
$plugins = Plugin::getAllEnabled();
$userOptions = array();
$navBarButtons = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$navBarButtons .= $p->navBarButtons();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $navBarButtons;
}
public static function navBarProfileButtons() {
$plugins = Plugin::getAllEnabled();
$userOptions = array();
$navBarButtons = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$navBarButtons .= $p->navBarProfileButtons();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $navBarButtons;
}
public static function navBar() {
$plugins = Plugin::getAllEnabled();
$userOptions = array();
$navBarButtons = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$navBarButtons .= $p->navBar();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $navBarButtons;
}
/**
* excecute update function at plugin and
* update plugin version at database
*/
public static function updatePlugin($name) {
$p = static::loadPlugin($name);
if(empty($p)){
return false;
}
$currentVersion = $p->getPluginVersion();
$uuid = $p->getUUID();
_error_log("AVideoPlugin::updatePlugin name=($name) uuid=($uuid) ");
if (method_exists($p, 'updateScript')) {
_error_log("AVideoPlugin::updatePlugin method_exists ", AVideoLog::$WARNING);
if ($p->updateScript())
Plugin::setCurrentVersionByUuid($uuid, $currentVersion);
else
return false;
} else {
_error_log("AVideoPlugin::updatePlugin method NOT exists ", AVideoLog::$WARNING);
Plugin::setCurrentVersionByUuid($uuid, $currentVersion);
}
return true;
}
public static function getCurrentVersion($name) {
$p = static::loadPlugin($name);
$uuid = $p->getUUID();
return Plugin::getCurrentVersionByUuid($uuid);
}
/**
*
* @param type $name
* @param type $version
* @return type
* -1 if your plugin is lower,
* 0 if they are equal, and
* 1 if your plugin is greater.
*/
public static function compareVersion($name, $version) {
$currentVersion = self::getCurrentVersion($name);
return version_compare($currentVersion, $version);
}
public static function getSwitchButton($name) {
global $global;
$p = static::loadPlugin($name);
$btn = "";
if (!empty($p)) {
$uid = uniqid();
$btn = '
';
}
return $btn;
}
public static function getAllVideosExcludeVideosIDArray() {
$plugins = Plugin::getAllEnabled();
$array = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$array = array_merge($array, $p->getAllVideosExcludeVideosIDArray());
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $array;
}
public static function userCanUpload($users_id) {
if (empty($users_id)) {
return false;
}
$resp = true;
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$can = $p->userCanUpload($users_id);
if (!empty($can)) {
if ($can < 0) {
_error_log("userCanUpload: DENIED The plugin {$value['dirName']} said the user ({$users_id}) can NOT upload a video ");
$resp = false;
}
if ($can > 0) {
_error_log("userCanUpload: SUCCESS The plugin {$value['dirName']} said the user ({$users_id}) can upload a video ");
return true;
}
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $resp;
}
public static function userCanWatchVideo($users_id, $videos_id) {
global $userCanWatchVideoFunction;
if(!isset($userCanWatchVideoFunction)){
$userCanWatchVideoFunction = array();
}
if(!isset($userCanWatchVideoFunction[$users_id])){
$userCanWatchVideoFunction[$users_id] = array();
}
if(isset($userCanWatchVideoFunction[$users_id][$videos_id])){
return $userCanWatchVideoFunction[$users_id][$videos_id];
}
$cacheName = "userCanWatchVideo($users_id, $videos_id)";
$cache = ObjectYPT::getSessionCache($cacheName, 600);
if(isset($cache)){
return $cache;
}
$plugins = Plugin::getAllEnabled();
$resp = Video::userGroupAndVideoGroupMatch($users_id, $videos_id);
$video = new Video("", "", $videos_id);
if (empty($video)) {
_error_log("userCanWatchVideo: the usergroup and the video group does not match, User = $users_id, video = $videos_id)");
$userCanWatchVideoFunction[$users_id][$videos_id] = false;
ObjectYPT::setSessionCache($cacheName, false);
return false;
}
// check if the video is for paid plans only
if ($video->getOnly_for_paid()) {
_error_log("userCanWatchVideo: the video ({$videos_id}) is set Only_for_paid = true)");
$resp = false;
}
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$can = $p->userCanWatchVideo($users_id, $videos_id);
if (!empty($can)) {
if ($can < 0) {
_error_log("userCanWatchVideo: DENIED The plugin {$value['dirName']} said the user ({$users_id}) can NOT watch the video ({$videos_id})");
$resp = false;
}
if ($can > 0) {
_error_log("userCanWatchVideo: SUCCESS The plugin {$value['dirName']} said the user ({$users_id}) can watch the video ({$videos_id})");
$userCanWatchVideoFunction[$users_id][$videos_id] = true;
ObjectYPT::setSessionCache($cacheName, true);
return true;
}
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
if (!empty($users_id)) {
_error_log("userCanWatchVideo: No plugins approve user ({$users_id}) watch the video ({$videos_id}) ");
}
$userCanWatchVideoFunction[$users_id][$videos_id] = $resp;
ObjectYPT::setSessionCache($cacheName, $resp);
return $resp;
}
public static function userCanWatchVideoWithAds($users_id, $videos_id) {
global $userCanWatchVideoWithAdsFunction;
$users_id = intval($users_id);
if(!isset($userCanWatchVideoWithAdsFunction)){
$userCanWatchVideoWithAdsFunction = array();
}
if(!isset($userCanWatchVideoWithAdsFunction[$users_id])){
$userCanWatchVideoWithAdsFunction[$users_id] = array();
}
if(isset($userCanWatchVideoWithAdsFunction[$users_id][$videos_id])){
return $userCanWatchVideoWithAdsFunction[$users_id][$videos_id];
}
$plugins = Plugin::getAllEnabled();
$resp = Video::userGroupAndVideoGroupMatch($users_id, $videos_id);
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$can = $p->userCanWatchVideoWithAds($users_id, $videos_id);
if (!empty($can)) {
$resp = $can > 0 ? true : false;
if ($resp) {
_error_log("userCanWatchVideoWithAds the plugin ({$value['dirName']}) said user ({$users_id}) can watch");
$userCanWatchVideoWithAdsFunction[$users_id][$videos_id] = true;
return true;
} else {
//_error_log("userCanWatchVideoWithAds: users_id = $users_id, videos_id = $videos_id {$value['dirName']} said no");
}
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
$userCanWatchVideoWithAdsFunction[$users_id][$videos_id] = $resp;
return $resp;
}
public static function showAds($videos_id) {
global $_showAds;
if(!isset($_showAds)){
$_showAds = array();
}
if(isset($_showAds[$videos_id])){
return $_showAds[$videos_id];
}
$plugins = Plugin::getAllEnabled();
$resp = true;
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$showAds = $p->showAds($videos_id);
if (!$showAds) {
_error_log("showAds: {$value['dirName']} said NOT to show ads on {$videos_id}");
$_showAds[$videos_id] = false;
return false;
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
$_showAds[$videos_id] = $resp;
return $resp;
}
/**
* In case some plugin needs to play a video that is not allowed for some reason.
* A plugin can replace the getVideo method from the youtubeMode page
* @return type
*/
public static function getVideo() {
$plugins = Plugin::getAllEnabled();
$resp = null;
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$video = $p->getVideo();
if (!empty($video)) {
return $video;
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $resp;
}
public static function onUserSignIn($users_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->onUserSignIn($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function onUserSignup($users_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->onUserSignup($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
public static function onLiveStream($users_id, $live_servers_id) {
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$p->onLiveStream($users_id, $live_servers_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
}
+
+ public static function onUserSocketConnect($users_id, $data) {
+ _mysql_connect();
+ $plugins = Plugin::getAllEnabled();
+ foreach ($plugins as $value) {
+ self::YPTstart();
+ $p = static::loadPlugin($value['dirName']);
+ if (is_object($p)) {
+ $p->onUserSocketConnect($users_id, $data);
+ }
+ self::YPTend("{$value['dirName']}::" . __FUNCTION__);
+ }
+ _mysql_close();
+ }
+
+ public static function onUserSocketDisconnect($users_id, $data) {
+ _mysql_connect();
+ $plugins = Plugin::getAllEnabled();
+ foreach ($plugins as $value) {
+ self::YPTstart();
+ $p = static::loadPlugin($value['dirName']);
+ if (is_object($p)) {
+ $p->onUserSocketConnect($users_id, $data);
+ }
+ self::YPTend("{$value['dirName']}::" . __FUNCTION__);
+ }
+ _mysql_close();
+ }
public static function thumbsOverlay($videos_id) {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->thumbsOverlay($videos_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function profileTabName($users_id) {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->profileTabName($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function profileTabContent($users_id) {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->profileTabContent($users_id);
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getVideoTags($videos_id) {
global $global, $advancedCustom;
if (empty($videos_id) || !empty($global['disableVideoTags']) || !empty($advancedCustom->disableVideoTags)) {
return array();
}
global $_getVideoTags;
if (empty($_getVideoTags)) {
$_getVideoTags = array();
}
if (isset($_getVideoTags[$videos_id])) {
$array = $_getVideoTags[$videos_id];
} else {
$name = "getVideoTags{$videos_id}";
$array = ObjectYPT::getCache($name, 86400);
//_error_log("getVideoTags $name ".(empty($array)?"new":"old"));
if (empty($array)) {
TimeLogStart("AVideoPlugin::getVideoTags($videos_id)");
$plugins = Plugin::getAllEnabled();
$array = array();
foreach ($plugins as $value) {
$TimeLog = "AVideoPlugin::getVideoTags($videos_id) {$value['dirName']} ";
TimeLogStart($TimeLog);
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$array = array_merge($array, $p->getVideoTags($videos_id));
}
TimeLogEnd($TimeLog, __LINE__);
}
TimeLogEnd("AVideoPlugin::getVideoTags($videos_id)", __LINE__);
ObjectYPT::setCache($name, $array);
$_getVideoTags[$videos_id] = $array;
} else {
//$array = object_to_array($array);
}
}
return $array;
}
public static function deleteVideoTags($videos_id) {
if (empty($videos_id)) {
return false;
}
$name = "getVideoTags{$videos_id}";
_error_log("deleteVideoTags {$name}");
ObjectYPT::deleteSessionCache($name);
return ObjectYPT::deleteCache($name);
}
public static function getVideoWhereClause() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getVideoWhereClause();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosAddNew() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosAddNew();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function saveVideosAddNew($post, $videos_id) {
$plugins = Plugin::getAllEnabled();
$r = true;
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r = $p->saveVideosAddNew($post, $videos_id) && $r;
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosReset() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosReset();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosEdit() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosEdit();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosEditField() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosEditField();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosJavaScripts() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosJavaScripts();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosTab() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosTab();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getManagerVideosBody() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getManagerVideosBody();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getAllVideosArray($videos_id) {
$plugins = Plugin::getAllEnabled();
$r = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r = array_merge($r, $p->getAllVideosArray($videos_id));
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function getUploadMenuButton() {
$plugins = Plugin::getAllEnabled();
$r = "";
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$r .= $p->getUploadMenuButton();
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return $r;
}
public static function dataSetup() {
$plugins = Plugin::getAllEnabled();
$r = array();
foreach ($plugins as $value) {
self::YPTstart();
$p = static::loadPlugin($value['dirName']);
if (is_object($p)) {
$data = $p->dataSetup();
if (!empty($data)) {
$r[] = $data;
}
}
self::YPTend("{$value['dirName']}::" . __FUNCTION__);
}
return implode(",", $r);
}
public static function getPluginsOnByDefault($getUUID = true) {
if (empty($getUUID)) {
return array(
'CustomizeUser', // CustomizeUser
'CustomizeAdvanced', // CustomizeAdvanced
'Layout', // Layout
'PlayerSkins', // PlayerSkins
'Permissions', // Permissions
);
} else {
return array(
'55a4fa56-8a30-48d4-a0fb-8aa6b3fuser3', // CustomizeUser
'55a4fa56-8a30-48d4-a0fb-8aa6b3f69033', // CustomizeAdvanced
'layout84-8f5a-4d1b-b912-172c608bf9e3', // Layout
'e9a568e6-ef61-4dcc-aad0-0109e9be8e36', // PlayerSkins
'Permissions-5ee8405eaaa16', // Permissions
);
}
}
public static function getPluginsNameOnByDefaultFromUUID($UUID) {
$UUIDs = self::getPluginsOnByDefault();
$key = array_search($UUID, $UUIDs);
if($key===false){
return false;
}
$names = self::getPluginsOnByDefault(false);
if (empty($names[$key])) {
return false;
}
return $names[$key];
}
public static function isPluginOnByDefault($UUID) {
$UUIDs = self::getPluginsOnByDefault();
return in_array($UUID, $UUIDs);
}
static function fixName($name){
if($name==='Programs'){
return 'PlayLists';
}
return $name;
}
}
class YouPHPTubePlugin extends AVideoPlugin {
}
diff --git a/plugin/Live/Live.php b/plugin/Live/Live.php
index 131c8b366..c10a144c5 100644
--- a/plugin/Live/Live.php
+++ b/plugin/Live/Live.php
@@ -1,1448 +1,1476 @@
and receive HLS streaming from servers";
$lu = AVideoPlugin::loadPlugin("LiveUsers");
if (!empty($lu)) {
if (version_compare($lu->getPluginVersion(), "2.0") < 0) {
$desc .= "You MUST update your LiveUsers plugin to version 2.0 or greater
";
}
}
return $desc;
}
public function getName() {
return "Live";
}
public function getHTMLMenuRight() {
global $global;
$buttonTitle = $this->getButtonTitle();
$obj = $this->getDataObject();
if (!empty($obj->hideTopButton)) {
return '';
}
include $global['systemRootPath'] . 'plugin/Live/view/menuRight.php';
}
public function getUUID() {
return "e06b161c-cbd0-4c1d-a484-71018efa2f35";
}
public function getPluginVersion() {
return "5.3";
}
public function updateScript() {
global $global;
//update version 2.0
$sql = "SELECT 1 FROM live_transmitions_history LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
sqlDal::writeSql(file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV2.0.sql'));
}
//update version 3.0
$sql = "SELECT 1 FROM live_transmition_history_log LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
sqlDal::writeSql(file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV3.0.sql'));
}
//update version 4.0
$sql = "SELECT 1 FROM live_servers LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV4.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.0
$sql = "SELECT 1 FROM live_restreams LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.1
if (AVideoPlugin::compareVersion($this->getName(), "5.1") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.1.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.2
if (AVideoPlugin::compareVersion($this->getName(), "5.2") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.2.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.2
if (AVideoPlugin::compareVersion($this->getName(), "6.0") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV6.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
return true;
}
public function getEmptyDataObject() {
global $global;
$server = parse_url($global['webSiteRootURL']);
$scheme = "http";
$port = "8080";
if (strtolower($server["scheme"]) == "https") {
$scheme = "https";
$port = "8443";
}
$obj = new stdClass();
$obj->button_title = "LIVE";
self::addDataObjectHelper('button_title', 'Button Title', 'This is the title that will appear in your button to enter in the Live panel');
$obj->server = "rtmp://{$server['host']}/live";
self::addDataObjectHelper('server', 'RTMP Server URL', 'Usually it is ' . "rtmp://{$server['host']}/live");
$obj->playerServer = "{$scheme}://{$server['host']}:{$port}/live";
self::addDataObjectHelper('playerServer', 'Player URL', 'This is a URL to your NGINX server, this URL will be used by the HTML5 player, If your site is HTTPS your player URL MUST be HTTPS as well, usually it is ' . "{$scheme}://{$server['host']}:{$port}/live");
$obj->stats = "{$scheme}://{$server['host']}:{$port}/stat";
self::addDataObjectHelper('stats', 'Stats Page URL', 'When you installed the NGINX you also install the stat.xsl, we will use it to grab the information when you have livestreams running, usually it is ' . "{$scheme}://{$server['host']}:{$port}/stat");
$obj->restreamerURL = "{$global['webSiteRootURL']}plugin/Live/standAloneFiles/restreamer.json.php";
self::addDataObjectHelper('restreamerURL', 'Restreamer URL', 'https://github.com/WWBN/AVideo/wiki/Restream');
$obj->controlURL = "{$global['webSiteRootURL']}plugin/Live/standAloneFiles/control.json.php";
self::addDataObjectHelper('controlURL', 'Control URL', 'Still under development');
$obj->disableRestream = false;
self::addDataObjectHelper('disableRestream', 'Disable Restream', 'If you check this, we will not send requests to your Restreamer URL');
$obj->disableDVR = false;
self::addDataObjectHelper('disableDVR', 'Disable DVR', 'Enable or disable the DVR Feature, you can control the DVR length in your nginx.conf on the parameter hls_playlist_length');
$obj->disableGifThumbs = false;
self::addDataObjectHelper('disableGifThumbs', 'Disable Gif Thumbs', 'This option will disable the Animated Gif render, it will save some hardware capacity from your encoder and may speedup your page');
$obj->disableLiveThumbs = false;
self::addDataObjectHelper('disableLiveThumbs', 'Disable Live thumbnails', 'This option will disable the çive image extraction and will use the user static image, it will save some hardware capacity from your encoder and may speedup your page');
$obj->hideTopButton = false;
self::addDataObjectHelper('hideTopButton', 'Hide Top Button', 'This will hide the "Go Live" button on the top menu bar');
$obj->useAadaptiveMode = false;
self::addDataObjectHelper('useAadaptiveMode', 'Adaptive mode', 'https://github.com/WWBN/AVideo/wiki/Adaptive-Bitrates-on-Livestream');
$obj->protectLive = false;
self::addDataObjectHelper('protectLive', 'Live Protection', 'With this your encryption key will be protected, and only your site player will be able to play your videos, download tools will not be able to download your video. if you want to share your live externally you can use the embed and you will still be protected. but if you want to use the m3u8 file you must disable this');
$obj->experimentalWebcam = false;
self::addDataObjectHelper('experimentalWebcam', 'Experimental Webcam', 'Requires flash and it is deprecated, will be removed. not recommend to enable it.');
$obj->doNotShowLiveOnVideosList = false;
self::addDataObjectHelper('doNotShowLiveOnVideosList', 'Do not show live on videos list', 'We will not show the live thumbs on the main Gallery page');
$obj->doNotShowLiveOnCategoryList = false;
self::addDataObjectHelper('doNotShowLiveOnCategoryList', 'Do not show live on site category list', 'We will not show the live thumbs on the main Gallery page');
$obj->doNotShowOfflineLiveOnCategoryList = false;
self::addDataObjectHelper('doNotShowOfflineLiveOnCategoryList', 'Do not show offline lives on site category list', 'We will not show the live thumbs on the main Gallery page if it is offline');
$obj->limitLiveOnVideosList = 12;
self::addDataObjectHelper('limitLiveOnVideosList', 'Videos List Limit', 'This will limit the maximum of videos that you will see in the Videos page');
//$obj->doNotShowGoLiveButton = false;
//self::addDataObjectHelper('doNotShowGoLiveButton', 'Hide Top Button', 'This will hide the "Go Live" button on the top menu bar');
$obj->doNotProcessNotifications = false;
self::addDataObjectHelper('doNotProcessNotifications', 'Do not show notifications', 'Do not show the notification on the top bar');
$obj->useLiveServers = false;
self::addDataObjectHelper('useLiveServers', 'Use Live Servers', 'Check this if you will use External Live Servers https://github.com/WWBN/AVideo/wiki/Live-Plugin#livestream-server-balance ');
$obj->disableMeetCamera = false;
self::addDataObjectHelper('disableMeetCamera', 'Disable Meet camera', 'This requires out Meet Server, with the Meet camera you can use your PC webcam directly in the webpage or mobile to make livestreams');
$obj->playLiveInFullScreen = false;
self::addDataObjectHelper('playLiveInFullScreen', 'Play Livestream in Full Screen');
$obj->playLiveInFullScreenOnIframe = false;
self::addDataObjectHelper('playLiveInFullScreenOnIframe', 'Play Livestream in Full Screen on IFrame');
$obj->hls_path = "/HLS/live";
self::addDataObjectHelper('hls_path', 'HLS Path URL', 'Used only when we stop a Live, we use this path to delete the files');
$obj->requestStatsTimout = 4; // if the server does not respond we stop wait
self::addDataObjectHelper('requestStatsTimout', 'Stats Timout', 'If a remote server (stats page) does not respond we stop waiting after this timeout');
$obj->cacheStatsTimout = 15; // we will cache the result
self::addDataObjectHelper('cacheStatsTimout', 'Stats Cache Timeout', 'we will cache the result, this will save some resources');
$obj->requestStatsInterval = 15; // how many seconds untill request the stats again
self::addDataObjectHelper('requestStatsInterval', 'Stats Request Interval', 'how many seconds until request the stats again');
$obj->streamDeniedMsg = "You can not stream live videos";
self::addDataObjectHelper('streamDeniedMsg', 'Denied Message', 'We will show this message when a user is not allowed so watch a livestream');
return $obj;
}
public function getHeadCode() {
global $global;
$obj = $this->getDataObject();
// preload image
$js = "";
$css = '';
if (!empty($obj->playLiveInFullScreen)) {
if ((isLive() || isEmbed()) && canFullScreen()) {
$css .= ' ';
$css .= '';
}
$js .= '';
$css .= '';
}
return $js . $css;
}
public function getFooterCode() {
$obj = $this->getDataObject();
global $global;
$js = '';
if (!empty($obj->playLiveInFullScreen)) {
$js = '';
$js .= '';
}else
if (!empty($obj->playLiveInFullScreenOnIframe)) {
$js = '';
$js .= '';
}
-
+ include $global['systemRootPath'].'plugin/Live/view/footer.php';
return $js;
}
public function getButtonTitle() {
$o = $this->getDataObject();
return $o->button_title;
}
public function getKey() {
$o = $this->getDataObject();
return $o->key;
}
static function getDestinationApplicationName() {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$app}?p=" . User::getUserPass();
}
static function getDestinationHost() {
$server = self::getServer();
$host = parse_url($server, PHP_URL_HOST);
return $host;
}
static function getDestinationPort() {
$server = self::getServer();
$port = parse_url($server, PHP_URL_PORT);
if (empty($port)) {
$port = 1935;
}
return $port;
}
static function getServer($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getRtmp_server())) {
return $ls->getRtmp_server();
}
}
return $obj->server;
}
static function getDropURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=drop_publisher&app={$app}&name={$key}&token=" . getToken(60);
}
static function getIsRecording($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=is_recording&app={$app}&name={$key}&token=" . getToken(60);
}
static function getStartRecordURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=record_start&app={$app}&name={$key}&token=" . getToken(60);
}
static function getStopRecordURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
return "{$domain}?command=record_stop&app={$app}&name={$key}&token=" . getToken(60);
}
static function getButton($command, $live_transmition_id, $live_servers_id = 0, $iconsOnly = false, $label = "", $class = "", $tooltip = "") {
if (!User::canStream()) {
return "";
}
global $global;
$id = "getButton" . uniqid();
if (empty($live_servers_id)) {
$live_servers_id = self::getLiveServersIdRequest();
}
switch ($command) {
case "record_start":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-video";
if (empty($label)) {
$label = __("Start Record");
}
if (empty($tooltip)) {
$tooltip = __("Start Record");
}
break;
case "record_stop":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-video-slash";
if (empty($label)) {
$label = __("Stop Record");
}
if (empty($tooltip)) {
$tooltip = __("Stop Record");
}
break;
case "drop_publisher":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-wifi";
if (empty($label)) {
$label = __("Disconnect Livestream");
}
if (empty($tooltip)) {
$tooltip = __("Disconnect Livestream");
}
break;
case "drop_publisher_reset_key":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-key";
if (empty($label)) {
$label = __("Disconnect Livestream");
}
if (empty($tooltip)) {
$tooltip = __("Disconnect Livestream") . __(" and also reset the stream name/key");
}
break;
default:
return '';
}
if ($iconsOnly) {
$label = "";
}
$html = " {$label}";
$html .= "";
$html .= " ";
return $html;
}
static function getRecordControlls($live_transmition_id, $live_servers_id = 0, $iconsOnly = false) {
if (!User::canStream()) {
return "";
}
$btn = "";
$btn .= self::getButton("record_start", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_stop", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= "
";
return $btn;
}
static function getAllControlls($live_transmition_id, $live_servers_id = 0, $iconsOnly = false) {
if (!User::canStream()) {
return "";
}
$btn = "";
//$btn .= self::getButton("drop_publisher", $live_transmition_id, $live_servers_id);
$btn .= self::getButton("drop_publisher_reset_key", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_start", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_stop", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= "
";
return $btn;
}
static function getRestreamer($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getRestreamerURL())) {
return $ls->getRestreamerURL();
}
}
return $obj->restreamerURL;
}
static function getControl($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->controlURL)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getControlURL())) {
return $ls->getControlURL();
}
}
return $obj->controlURL;
}
static function getRTMPLink($users_id) {
if (!User::isLogged() || ($users_id !== User::getId() && !User::isAdmin())) {
return false;
}
$user = new User($users_id);
$trasnmition = LiveTransmition::createTransmitionIfNeed($users_id);
return self::getServer() . "?p=" . $user->getPassword() . "/" . $trasnmition['key'];
}
static function getPlayerServer() {
$obj = AVideoPlugin::getObjectData("Live");
$url = $obj->playerServer;
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
if (!empty($ls->getPlayerServer())) {
$url = $ls->getPlayerServer();
}
}
$url = str_replace("encoder.gdrive.local", "192.168.1.18", $url);
return $url;
}
static function getUseAadaptiveMode() {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
return $ls->getUseAadaptiveMode();
}
return $obj->useAadaptiveMode;
}
static function getRemoteFile() {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
return $ls->getGetRemoteFile();
}
return false;
}
static function getRemoteFileFromRTMPHost($rtmpHostURI) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$live_servers_id = Live_servers::getServerIdFromRTMPHost($rtmpHostURI);
if ($live_servers_id) {
$ls = new Live_servers($live_servers_id);
return $ls->getGetRemoteFile();
}
}
return false;
}
static function getLiveServersIdRequest() {
if (empty($_REQUEST['live_servers_id'])) {
return 0;
}
return intval($_REQUEST['live_servers_id']);
}
static function getM3U8File($uuid, $doNotProtect = false) {
global $global;
$o = AVideoPlugin::getObjectData("Live");
$playerServer = self::getPlayerServer();
$live_servers_id = self::getLiveServersIdRequest();
$liveServer = new Live_servers($live_servers_id);
if ($liveServer->getStats_url()) {
$o->protectLive = $liveServer->getProtectLive();
$o->useAadaptiveMode = $liveServer->getUseAadaptiveMode();
}
$uuid = LiveTransmition::keyNameFix($uuid);
if ($o->protectLive && empty($doNotProtect)) {
return "{$global['webSiteRootURL']}plugin/Live/m3u8.php?live_servers_id={$live_servers_id}&uuid=" . encryptString($uuid);
} else if ($o->useAadaptiveMode) {
return $playerServer . "/{$uuid}.m3u8";
} else {
return $playerServer . "/{$uuid}/index.m3u8";
}
}
public function getDisableGifThumbs() {
$o = $this->getDataObject();
return $o->disableGifThumbs;
}
public function getStatsURL($live_servers_id = 0) {
global $global;
$o = $this->getDataObject();
if (!empty($live_servers_id)) {
$liveServer = new Live_servers($live_servers_id);
if ($liveServer->getStats_url()) {
return $liveServer->getStats_url();
}
}
return $o->stats;
}
public function getChat($uuid) {
global $global;
//check if LiveChat Plugin is available
$filename = $global['systemRootPath'] . 'plugin/LiveChat/LiveChat.php';
if (file_exists($filename)) {
require_once $filename;
LiveChat::includeChatPanel($uuid);
}
}
function getStatsObject($live_servers_id = 0) {
if (!function_exists('simplexml_load_file')) {
_error_log("Live::getStatsObject: You need to install the simplexml_load_file function to be able to see the Live stats", AVideoLog::$ERROR);
return false;
}
global $getStatsObject;
if (!empty($getStatsObject[$live_servers_id])) {
return $getStatsObject[$live_servers_id];
}
$o = $this->getDataObject();
if ($o->doNotProcessNotifications) {
$xml = new stdClass();
$xml->server = new stdClass();
$xml->server->application = array();
return $xml;
}
if (empty($o->requestStatsTimout)) {
$o->requestStatsTimout = 2;
}
ini_set('allow_url_fopen ', 'ON');
$url = $this->getStatsURL($live_servers_id);
if (!empty($_SESSION['getStatsObjectRequestStatsTimout'][$url])) {
_error_log("Live::getStatsObject RTMP Server ($url) is NOT responding we will wait less from now on => live_servers_id = ($live_servers_id) ");
// if the server already fail, do not wait mutch for it next time, just wait 0.5 seconds
$o->requestStatsTimout = $_SESSION['getStatsObjectRequestStatsTimout'][$url];
}
$data = $this->get_data($url, $o->requestStatsTimout);
if (empty($data)) {
_session_start();
if (empty($_SESSION['getStatsObjectRequestStatsTimout'])) {
$_SESSION['getStatsObjectRequestStatsTimout'] = array();
}
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = $o->requestStatsTimout-1;
if($_SESSION['getStatsObjectRequestStatsTimout'][$url]<1){
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = 2;
}
_error_log("Live::getStatsObject RTMP Server ($url) is OFFLINE, timeout=({$o->requestStatsTimout}) we could not connect on it => live_servers_id = ($live_servers_id) ", AVideoLog::$ERROR);
$data = 'The RTMP Server is Unavailable 0 ';
} else {
if (!empty($_SESSION['getStatsObjectRequestStatsTimout'][$url])) {
_error_log("Live::getStatsObject RTMP Server ($url) is respond again => live_servers_id = ($live_servers_id) ");
// the server respont again, wait the default time
_session_start();
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = 0;
unset($_SESSION['getStatsObjectRequestStatsTimout'][$url]);
}
}
$xml = simplexml_load_string($data);
$getStatsObject[$live_servers_id] = $xml;
return $xml;
}
function get_data($url, $timeout) {
try {
$content = url_get_contents($url, "", $timeout);
return $content;
} catch (Exception $exc) {
_error_log($exc->getTraceAsString());
}
return false;
}
public function getChartTabs() {
return ' ' . __('Live videos') . ' ';
}
public function getChartContent() {
global $global;
include $global['systemRootPath'] . 'plugin/Live/report.php';
}
static public function saveHistoryLog($key) {
// get the latest history for this key
$latest = LiveTransmitionHistory::getLatest($key);
if (!empty($latest)) {
LiveTransmitionHistoryLog::addLog($latest['id']);
}
}
public function dataSetup() {
$obj = $this->getDataObject();
if (!isLive() || $obj->disableDVR) {
return "";
}
return "liveui: true";
}
static function stopLive($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/drop/publisher?app={$appName}&name=$key";
url_get_contents($url);
$dir = $obj->hls_path . "/$key";
if (is_dir($dir)) {
exec("rm -fR $dir");
rrmdir($dir);
}
}
}
// not implemented yet
static function startRecording($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/record/start?app={$appName}&name=$key";
url_get_contents($url);
}
}
static function getApplicationName() {
$obj = AVideoPlugin::getObjectData('Live');
$parts = explode("/", $obj->playerServer);
$live = end($parts);
if (empty($live)) {
$live = "live";
}
return $live;
}
// not implemented yet
static function stopRecording($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/record/stop?app={$appName}&name=$key";
url_get_contents($url);
}
}
static function getLinkToLiveFromUsers_id($users_id) {
$live_servers_id = self::getCurrentLiveServersId();
return self::getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id);
}
static function getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id) {
if (empty($users_id)) {
return false;
}
global $global;
$user = new User($users_id);
if (empty($user->getChannelName())) {
return false;
}
return self::getLinkToLiveFromChannelNameAndLiveServer($user->getChannelName(), $live_servers_id);
}
static function getLinkToLiveFromChannelNameAndLiveServer($channelName, $live_servers_id) {
global $global;
$live_servers_id = intval($live_servers_id);
$channelName = trim($channelName);
if (empty($channelName)) {
return false;
}
$playlists_id_live = "";
if (!empty($_REQUEST['playlists_id_live'])) {
$playlists_id_live = "?playlists_id_live=" . $_REQUEST['playlists_id_live'];
}
//return "{$global['webSiteRootURL']}plugin/Live/?live_servers_id={$live_servers_id}&c=" . urlencode($channelName);
return "{$global['webSiteRootURL']}live/{$live_servers_id}/" . urlencode($channelName) . $playlists_id_live;
}
static function getAvailableLiveServersId() {
$ls = self::getAvailableLiveServer();
if (empty($ls)) {
return 0;
} else {
return intval($ls->live_servers_id);
}
}
static function getLastServersIdFromUser($users_id) {
$last = LiveTransmitionHistory::getLatestFromUser($users_id);
if (empty($last)) {
return 0;
} else {
return intval($last['live_servers_id']);
}
}
static function getLinkToLiveFromUsers_idWithLastServersId($users_id) {
$live_servers_id = self::getLastServersIdFromUser($users_id);
return self::getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id);
}
static function getCurrentLiveServersId() {
$live_servers_id = self::getLiveServersIdRequest();
if ($live_servers_id) {
return $live_servers_id;
} else {
return self::getAvailableLiveServersId();
}
}
public function getVideosManagerListButtonTitle() {
global $global;
if (!User::isAdmin()) {
return "";
}
$btn = '
' . __("Live Info") . ' ';
return $btn;
}
public function getPluginMenu() {
global $global;
return ' ' . __('Edit Live Servers') . ' ';
}
- static function getStats() {
- global $getStatsLive;
+ static function getStats($force_recreate=false) {
+ global $getStatsLive, $_getStats, $getStatsObject;
+ if(!empty($force_recreate)){
+ unset($getStatsLive);
+ $_getStats = array();
+ $getStatsObject = array();
+ }
if (isset($getStatsLive)) {
return $getStatsLive;
}
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
$getStatsLive = self::_getStats(0);
return $getStatsLive;
} else if (!empty(Live::getLiveServersIdRequest())) {
$ls = new Live_servers(Live::getLiveServersIdRequest());
if (!empty($ls->getPlayerServer())) {
$server = self::_getStats($ls->getId());
$server->live_servers_id = $ls->getId();
$server->playerServer = $ls->getPlayerServer();
$getStatsLive = $server;
return $server;
}
}
$ls = Live_servers::getAllActive();
$liveServers = array();
$getLiveServersIdRequest = self::getLiveServersIdRequest();
foreach ($ls as $value) {
$server = Live_servers::getStatsFromId($value['id']);
if (!empty($server) && is_object($server)) {
$server->live_servers_id = $value['id'];
$server->playerServer = $value['playerServer'];
foreach ($server->applications as $key => $app) {
$_REQUEST['live_servers_id'] = $value['id'];
if (empty($app['key'])) {
$app['key'] = "";
}
$server->applications[$key]['m3u8'] = self::getM3U8File($app['key']);
+ $server->applications[$key]['isURL200'] = isURL200($server->applications[$key]['m3u8']);
}
$liveServers[] = $server;
} else {
_error_log("Live::getStats Live Server NOT found {$value['id']} " . json_encode($server) . " " . json_encode($value));
}
}
$_REQUEST['live_servers_id'] = $getLiveServersIdRequest;
$getStatsLive = $liveServers;
return $liveServers;
}
static function getAllServers() {
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
return array("id" => 0, "name" => __("Default"), "status" => "a", "rtmp_server" => $obj->server, 'playerServer' => $obj->playerServer, "stats_url" => $obj->stats, "disableDVR" => $obj->disableDVR, "disableGifThumbs" => $obj->disableGifThumbs, "useAadaptiveMode" => $obj->useAadaptiveMode, "protectLive" => $obj->protectLive, "getRemoteFile" => "");
} else {
return Live_servers::getAllActive();
}
}
static function getAvailableLiveServer() {
// create 1 min cache
$name = "Live::getAvailableLiveServer";
$return = ObjectYPT::getCache($name, 60);
if (empty($return)) {
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
$return = false;
} else {
$liveServers = self::getStats();
usort($liveServers, function($a, $b) {
if ($a->countLiveStream == $b->countLiveStream) {
return 0;
}
return ($a->countLiveStream < $b->countLiveStream) ? -1 : 1;
});
if (empty($liveServers[0])) {
_error_log("Live::getAvailableLiveServer we could not get server status, try to uncheck useLiveServers parameter from the Live plugin");
return array();
}
$return = $liveServers[0];
ObjectYPT::setCache($name, $return);
}
}
return $return;
}
static function canSeeLiveFromLiveKey($key) {
$lt = self::getLiveTransmitionObjectFromKey($key);
if (empty($lt)) {
return false;
}
return $lt->userCanSeeTransmition();
}
static function isAPrivateLiveFromLiveKey($key) {
$lt = self::getLiveTransmitionObjectFromKey($key);
if (empty($lt)) {
return false;
}
return $lt->isAPrivateLive();
}
static function getLiveTransmitionObjectFromKey($key) {
global $getLiveTransmitionObjectFromKey;
if (empty($getLiveTransmitionObjectFromKey)) {
$getLiveTransmitionObjectFromKey = array();
}
$parts = explode("_", $key);
if (empty($parts[0])) {
return false;
}
if (!isset($getLiveTransmitionObjectFromKey[$parts[0]])) {
$livet = LiveTransmition::keyExists($parts[0]);
if (empty($livet)) {
$getLiveTransmitionObjectFromKey[$parts[0]] = false;
} else {
$lt = new LiveTransmition($livet['id']);
$getLiveTransmitionObjectFromKey[$parts[0]] = $lt;
}
}
return $getLiveTransmitionObjectFromKey[$parts[0]];
}
static function _getStats($live_servers_id = 0) {
global $global, $_getStats;
if (empty($_REQUEST['name'])) {
//_error_log("Live::_getStats {$live_servers_id} GET " . json_encode($_GET));
//_error_log("Live::_getStats {$live_servers_id} POST " . json_encode($_POST));
//_error_log("Live::_getStats {$live_servers_id} REQUEST " . json_encode($_REQUEST));
$_REQUEST['name'] = "undefined";
}
if (!empty($_getStats[$live_servers_id][$_REQUEST['name']]) && is_object($_getStats[$live_servers_id][$_REQUEST['name']])) {
//_error_log("Live::_getStats cached result {$_REQUEST['name']} " . json_encode($_getStats[$live_servers_id][$_REQUEST['name']]));
return $_getStats[$live_servers_id][$_REQUEST['name']];
}
session_write_close();
$obj = new stdClass();
$obj->error = true;
$obj->msg = "OFFLINE";
$obj->nclients = 0;
$obj->applications = array();
$obj->hidden_applications = array();
$obj->name = $_REQUEST['name'];
$liveUsersEnabled = AVideoPlugin::isEnabledByName("LiveUsers");
$p = AVideoPlugin::loadPlugin("Live");
$xml = $p->getStatsObject($live_servers_id);
$xml = json_encode($xml);
$xml = json_decode($xml);
$stream = false;
$lifeStream = array();
//$obj->server = $xml->server;
if (!empty($xml->server->application) && !is_array($xml->server->application)) {
$application = $xml->server->application;
$xml->server->application = array();
$xml->server->application[] = $application;
}
foreach ($xml->server->application as $key => $application) {
if (!empty($application->live->stream)) {
if (empty($lifeStream)) {
$lifeStream = array();
}
$stream = $application->live->stream;
if (empty($application->live->stream->name) && !empty($application->live->stream[0]->name)) {
foreach ($application->live->stream as $stream) {
$lifeStream[] = $stream;
}
} else {
$lifeStream[] = $application->live->stream;
}
}
}
$obj->disableGif = $p->getDisableGifThumbs();
$obj->countLiveStream = count($lifeStream);
foreach ($lifeStream as $value) {
if (!empty($value->name)) {
$row = LiveTransmition::keyExists($value->name);
if (empty($row['users_id'])) {
continue;
}
if (!empty($row) && $value->name === $obj->name) {
$obj->msg = "ONLINE";
}
$title = $row['title'];
$u = new User($row['users_id']);
$hiddenName = preg_replace('/^(.{5})/', '*****', $value->name);
if (!self::canSeeLiveFromLiveKey($value->name)) {
$obj->hidden_applications[] = "{$row['channelName']} ($hiddenName} is a private live";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (private live)";
}
} else
if (empty($row) || empty($row['public'])) {
$obj->hidden_applications[] = "{$row['channelName']} ($hiddenName} is set to not be listed";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (set to not be listed)";
}
} else
if ($u->getStatus() !== 'a') {
$obj->hidden_applications[] = "{$row['channelName']} {$hiddenName} the user is inactive";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (user is inactive)";
}
}
$users = false;
if ($liveUsersEnabled) {
$filename = $global['systemRootPath'] . 'plugin/LiveUsers/Objects/LiveOnlineUsers.php';
if (file_exists($filename)) {
require_once $filename;
$liveUsers = new LiveOnlineUsers(0);
$users = $liveUsers->getUsersFromTransmitionKey($value->name, $live_servers_id);
}
}
$userName = $u->getNameIdentificationBd();
$user = $u->getUser();
$channelName = $u->getChannelName();
$photo = $u->getPhotoDB();
$poster = $global['webSiteRootURL'] . $p->getPosterImage($row['users_id'], $live_servers_id);
$playlists_id_live = 0;
if (preg_match("/.*_([0-9]+)/", $value->name, $matches)) {
if (!empty($matches[1])) {
$_REQUEST['playlists_id_live'] = intval($matches[1]);
$playlists_id_live = $_REQUEST['playlists_id_live'];
$photo = PlayLists::getImage($_REQUEST['playlists_id_live']);
$title = PlayLists::getNameOrSerieTitle($_REQUEST['playlists_id_live']);
}
}
$link = Live::getLinkToLiveFromChannelNameAndLiveServer($u->getChannelName(), $live_servers_id);
// this variable is to keep it compatible for Mobile app
$UserPhoto = $photo;
+ $key = LiveTransmition::keyNameFix($value->name);
+ $m3u8 = self::getM3U8File($key);
$obj->applications[] = array(
- "key" => LiveTransmition::keyNameFix($value->name),
+ "key" => $key,
"isPrivate" => self::isAPrivateLiveFromLiveKey($value->name),
"users" => $users,
"name" => $userName,
"user" => $user,
"photo" => $photo,
"UserPhoto" => $UserPhoto,
"title" => $title,
'channelName' => $channelName,
'poster' => $poster,
- 'link' => $link . (strpos($link, '?') !== false ? "&embed=1" : "?embed=1"),
+ 'link' => addQueryStringParameter($link, 'embed', 1),
'href' => $link,
- 'playlists_id_live' => $playlists_id_live
+ 'playlists_id_live' => $playlists_id_live,
+ 'm3u8' => $m3u8,
+ 'isURL200' => isURL200($m3u8)
);
if ($value->name === $obj->name) {
$obj->error = property_exists($value, 'publishing') ? false : true;
$obj->msg = (!$obj->error) ? "ONLINE" : "Waiting for Streamer";
$obj->stream = $value;
$obj->nclients = intval($value->nclients);
break;
}
}
}
$obj->error = false;
$_getStats[$live_servers_id][$_REQUEST['name']] = $obj;
//_error_log("Live::_getStats NON cached result {$_REQUEST['name']} " . json_encode($obj));
return $obj;
}
static function getImage($users_id, $live_servers_id, $playlists_id_live = 0) {
$p = AVideoPlugin::loadPlugin("Live");
if (self::isLive($users_id)) {
$url = $p->getLivePosterImage($users_id, $live_servers_id);
$url = addQueryStringParameter($url, "playlists_id_live", $playlists_id_live);
} else {
$file = self::getOfflineImage(false);
}
return $url;
}
- static function isLive($users_id, $live_servers_id = 0) {
+ static function isLive($users_id, $live_servers_id = 0, $force_recreate=false) {
if(empty($users_id)){
return false;
}
$key = self::getLiveKey($users_id);
- $json = self::getStats();
+ return self::isLiveAndIsReadyFromKey($key, $live_servers_id, $force_recreate=false);
+ }
+
+ static function isLiveFromKey($key, $live_servers_id = 0, $force_recreate=false) {
+ if(empty($key)){
+ return false;
+ }
+ $json = self::getStats($force_recreate);
if (!empty($json) && is_object($json) && !empty($json->applications)) {
foreach ($json->applications as $value) {
if (preg_match("/{$key}.*/", $value['key'])) {
if (empty($live_servers_id)) {
return true;
} else {
if ($value['live_servers_id'] == $live_servers_id) {
return true;
}
}
}
}
}
return false;
}
+
+ static function isLiveAndIsReadyFromKey($key, $live_servers_id = 0, $force_recreate=false) {
+ $m3u8 = self::getM3U8File($key);
+ $isLiveFromKey = self::isLiveFromKey($key, $live_servers_id, $force_recreate);
+ $is200 = isURL200($m3u8);
+ _error_log("isLiveFromKey: {$isLiveFromKey}");
+ _error_log("m3u8: {$m3u8}");
+ _error_log("is200: {$is200}");
+ return $isLiveFromKey && $is200;
+ }
static function getOnlineLivesFromUser($users_id) {
$key = self::getLiveKey($users_id);
$json = self::getStats();
$lives = array();
if (!empty($json) && is_object($json) && !empty($json->applications)) {
foreach ($json->applications as $value) {
if (preg_match("/{$key}.*/", $value['key'])) {
$lives[] = $value;
}
}
}
return $lives;
}
static function keyIsFromPlaylist($key) {
$parts = explode("_", $key);
if (empty($parts[1])) {
return false;
}
return array('key' => $parts[0], 'playlists_id' => $parts[1]);
}
static function getLiveKey($users_id) {
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
return $lt->getKey();
}
public function getImageGif($users_id, $live_servers_id = 0, $playlists_id_live = 0) {
global $global;
if (empty($live_servers_id)) {
$live_servers_id = self::getCurrentLiveServersId();
}
$u = new User($users_id);
$username = $u->getUser();
$file = "plugin/Live/getImage.php?live_servers_id={$live_servers_id}&u={$username}&format=gif";
$url = $global['webSiteRootURL'] . $file;
$url = addQueryStringParameter($url, "playlists_id_live", $playlists_id_live);
return $url;
}
public function getPosterImage($users_id, $live_servers_id) {
global $global;
$file = self::_getPosterImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = "plugin/Live/view/OnAir.jpg";
}
return $file;
}
public function getLivePosterImage($users_id, $live_servers_id = 0) {
global $global;
return $global['webSiteRootURL'] . self::getLivePosterImageRelativePath($users_id, $live_servers_id);
}
public function getLivePosterImageRelativePath($users_id, $live_servers_id = 0) {
global $global;
if (empty($live_servers_id)) {
$live_servers_id = self::getCurrentLiveServersId();
}
if (self::isLiveThumbsDisabled()) {
$file = self::_getPosterImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = "plugin/Live/view/OnAir.jpg";
}
} else {
$u = new User($users_id);
$username = $u->getUser();
$file = "plugin/Live/getImage.php?live_servers_id={$live_servers_id}&u={$username}&format=jpg";
}
return $file;
}
public static function isLiveThumbsDisabled() {
$obj = AVideoPlugin::getDataObject("Live");
if (!empty($obj->disableLiveThumbs)) {
return true;
}
return false;
}
public function getPosterThumbsImage($users_id, $live_servers_id) {
global $global;
$file = self::_getPosterThumbsImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = self::getOnAirImage(false);
}
return $file;
}
static function getOfflineImage($includeURL = true) {
global $global;
$img = "plugin/Live/view/Offline.jpg";
if ($includeURL) {
$img = "{$global['webSiteRootURL']}{$img}";
}
return $img;
}
static function getOnAirImage($includeURL = true) {
global $global;
$img = "plugin/Live/view/OnAir.jpg";
if ($includeURL) {
$img = "{$global['webSiteRootURL']}{$img}";
}
return $img;
}
public function _getPosterImage($users_id, $live_servers_id) {
$file = "videos/userPhoto/Live/user_{$users_id}_bg_{$live_servers_id}.jpg";
return $file;
}
public function _getPosterThumbsImage($users_id, $live_servers_id) {
$file = "videos/userPhoto/Live/user_{$users_id}_thumbs_{$live_servers_id}.jpg";
return $file;
}
public static function on_publish($liveTransmitionHistory_id) {
$obj = AVideoPlugin::getDataObject("Live");
if (empty($obj->disableRestream)) {
self::restream($liveTransmitionHistory_id);
}
}
public static function getRestreamObject($liveTransmitionHistory_id) {
if (empty($liveTransmitionHistory_id)) {
return false;
}
$lth = new LiveTransmitionHistory($liveTransmitionHistory_id);
if (empty($lth->getKey())) {
return false;
}
$_REQUEST['live_servers_id'] = $lth->getLive_servers_id();
$obj = new stdClass();
$obj->m3u8 = self::getM3U8File($lth->getKey(), true);
$obj->restreamerURL = self::getRestreamer($lth->getLive_servers_id());
$obj->restreamsDestinations = array();
$obj->token = getToken(60);
$obj->users_id = $lth->getUsers_id();
$rows = Live_restreams::getAllFromUser($lth->getUsers_id());
foreach ($rows as $value) {
$value['stream_url'] = rtrim($value['stream_url'], "/") . '/';
$obj->restreamsDestinations[] = "{$value['stream_url']}{$value['stream_key']}";
}
return $obj;
}
public static function restream($liveTransmitionHistory_id) {
ignore_user_abort(true);
ob_start();
header("Connection: close");
@header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
try {
$obj = self::getRestreamObject($liveTransmitionHistory_id);
if (empty($obj)) {
return false;
}
$data_string = json_encode($obj);
_error_log("Live:restream ({$obj->restreamerURL}) {$data_string}");
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $obj->restreamerURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output);
} catch (Exception $exc) {
_error_log("Live:restream " . $exc->getTraceAsString());
}
return false;
}
public static function canStreamWithMeet() {
if (!User::canStream()) {
return false;
}
if (!User::canCreateMeet()) {
return false;
}
$mobj = AVideoPlugin::getObjectDataIfEnabled("Meet");
if (empty($mobj)) {
return false;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("Live");
if (!empty($obj->disableMeetCamera)) {
return false;
}
return true;
}
public function getUploadMenuButton() {
global $global;
$obj = $this->getDataObject();
if (!empty($obj->doNotShowGoLiveButton) || !User::canStream()) {
return '';
}
$buttonTitle = $this->getButtonTitle();
//include $global['systemRootPath'] . 'plugin/Live/getUploadMenuButton.php';
}
public static function getAllVideos($status = "", $showOnlyLoggedUserVideos = false, $activeUsersOnly = true) {
global $global, $config, $advancedCustom;
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$status = str_replace("'", "", $status);
$sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified "
. " FROM live_transmitions as v "
. " LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$uid = intval(User::getId());
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$uid = intval($showOnlyLoggedUserVideos);
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
if ($status == "publicOnly") {
$sql .= " AND v.public = 1 ";
} elseif (!empty($status)) {
$sql .= " AND v.`public` = '{$status}'";
}
if (!empty($_GET['catName'])) {
- $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
+ $catName = $global['mysqli']->real_escape_string($_GET['catName']);
+ $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))";
}
if (!empty($_GET['modified'])) {
$_GET['modified'] = str_replace("'", "", $_GET['modified']);
$sql .= " AND v.modified >= '{$_GET['modified']}'";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if (strpos(strtolower($sql), 'limit') === false) {
if (!empty($_GET['limitOnceToOne'])) {
$sql .= " LIMIT 1";
unset($_GET['limitOnceToOne']);
}else{
$_REQUEST['rowCount'] = getRowCount();
if (!empty($_REQUEST['rowCount'])) {
$sql .= " LIMIT {$_REQUEST['rowCount']}";
} else {
_error_log("getAllVideos without limit " . json_encode(debug_backtrace()));
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = 100;
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
}
}
//echo $sql;exit;
//_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$videos = array();
if ($res != false) {
foreach ($fullData as $row) {
unset($row['password']);
unset($row['recoverPass']);
$row['live_servers_id'] = self::getLastServersIdFromUser($row['users_id']);
if (empty($otherInfo)) {
$otherInfo = array();
$otherInfo['category'] = xss_esc_back($row['category']);
$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']);
//$otherInfo['title'] = UTF8encode($row['title']);
$otherInfo['description'] = UTF8encode($row['description']);
$otherInfo['descriptionHTML'] = Video::htmlDescription($otherInfo['description']);
$otherInfo['filesize'] = 0;
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['rotation'] = 0;
$row['filename'] = '';
$row['type'] = 'live';
$row['duration'] = '';
$row['isWatchLater'] = 0;
$row['isFavorite'] = 0;
$row['views_count'] = 0;
$videos[] = $row;
}
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
}
diff --git a/plugin/Live/Objects/LiveTransmitionHistory.php b/plugin/Live/Objects/LiveTransmitionHistory.php
index d47a06188..02f6985a9 100644
--- a/plugin/Live/Objects/LiveTransmitionHistory.php
+++ b/plugin/Live/Objects/LiveTransmitionHistory.php
@@ -1,179 +1,281 @@
id;
}
function getTitle() {
return $this->title;
}
function getDescription() {
return $this->description;
}
function getKey() {
return $this->key;
}
function getCreated() {
return $this->created;
}
function getModified() {
return $this->modified;
}
function getUsers_id() {
return $this->users_id;
}
function setId($id) {
$this->id = $id;
}
function setTitle($title) {
global $global;
$title = $global['mysqli']->real_escape_string($title);
$this->title = $title;
}
function setDescription($description) {
global $global;
$description = $global['mysqli']->real_escape_string($description);
$this->description = $description;
}
function setKey($key) {
$this->key = $key;
}
function setCreated($created) {
$this->created = $created;
}
function setModified($modified) {
$this->modified = $modified;
}
function setUsers_id($users_id) {
$this->users_id = $users_id;
}
function getLive_servers_id() {
return intval($this->live_servers_id);
}
+ static function getApplicationObject($liveTransmitionHistory_id) {
+ global $global;
+ $lth = new LiveTransmitionHistory($liveTransmitionHistory_id);
+ $liveUsersEnabled = AVideoPlugin::isEnabledByName("LiveUsers");
+ $p = AVideoPlugin::loadPlugin("Live");
+ $obj = new stdClass();
+ $users_id = $lth->getUsers_id();
+ $u = new User($users_id);
+ $live_servers_id = $lth->getLive_servers_id();
+ $key = $lth->getKey();
+ $title = $lth->getTitle();
+ $photo = $u->getPhotoDB();
+ $m3u8 = Live::getM3U8File($key);
+ $poster = $global['webSiteRootURL'] . $p->getPosterImage($users_id, $live_servers_id);
+ $playlists_id_live = 0;
+ if (preg_match("/.*_([0-9]+)/", $key, $matches)) {
+ if (!empty($matches[1])) {
+ $_REQUEST['playlists_id_live'] = intval($matches[1]);
+ $playlists_id_live = $_REQUEST['playlists_id_live'];
+ $photo = PlayLists::getImage($_REQUEST['playlists_id_live']);
+ $title = PlayLists::getNameOrSerieTitle($_REQUEST['playlists_id_live']);
+ }
+ }
+
+ $obj->UserPhoto = $u->getPhotoDB();
+ $obj->photo = $photo;
+ $obj->channelName = $u->getChannelName();
+ $obj->href = Live::getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id);
+ $obj->key = $key;
+ $obj->isPrivate = Live::isAPrivateLiveFromLiveKey($obj->key);
+ $obj->link = addQueryStringParameter($obj->href, 'embed', 1);
+ $obj->name = $u->getNameIdentificationBd();
+ $obj->playlists_id_live = $playlists_id_live;
+ $obj->poster = Live::isAPrivateLiveFromLiveKey($obj->key);
+ $obj->title = $title;
+ $obj->user = $u->getUser();
+ $users = false;
+ if ($liveUsersEnabled) {
+ $filename = $global['systemRootPath'] . 'plugin/LiveUsers/Objects/LiveOnlineUsers.php';
+ if (file_exists($filename)) {
+ require_once $filename;
+ $liveUsers = new LiveOnlineUsers(0);
+ $users = $liveUsers->getUsersFromTransmitionKey($key, $live_servers_id);
+ }
+ }
+ $obj->users = $users;
+
+ $obj->m3u8 =$m3u8;
+ $obj->isURL200 = isURL200($m3u8);
+
+ return $obj;
+ }
+
+ static function getStatsAndAddApplication($liveTransmitionHistory_id) {
+ $stats = Live::getStats();
+ $lth = new LiveTransmitionHistory($liveTransmitionHistory_id);
+
+ $key = $lth->getKey();
+ foreach ($stats->applications as $value) {
+ $value = object_to_array($value);
+ if($value['key']==$key){ // application is already in the list
+ return $stats;
+ }
+ }
+ foreach ($stats->hidden_applications as $value) {
+ $value = object_to_array($value);
+ if($value['key']==$key){ // application is already in the list
+ return $stats;
+ }
+ }
+
+ $application = self::getApplicationObject($liveTransmitionHistory_id);
+ if ($application->isPrivate) {
+ $stats->hidden_applications[] = $application;
+ } else {
+ $stats->applications[] = $application;
+ }
+ $stats->countLiveStream++;
+ return $stats;
+ }
+
+ static function getStatsAndRemoveApplication($liveTransmitionHistory_id) {
+ $stats = Live::getStats();
+ $lth = new LiveTransmitionHistory($liveTransmitionHistory_id);
+
+ $key = $lth->getKey();
+ foreach ($stats->applications as $k => $value) {
+ $value = object_to_array($value);
+ if($value['key']==$key){ // application is already in the list
+ unset($stats->applications[$k]);
+ $stats->countLiveStream--;
+ }
+ }
+ foreach ($stats->hidden_applications as $k => $value) {
+ $value = object_to_array($value);
+ if($value['key']==$key){ // application is already in the list
+ unset($stats->hidden_applications[$k]);
+ }
+ }
+
+ return $stats;
+ }
+
function setLive_servers_id($live_servers_id) {
$this->live_servers_id = intval($live_servers_id);
}
function getAllFromUser($users_id) {
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE users_id = ? ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql, "i", array($users_id));
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$log = LiveTransmitionHistoryLog::getAllFromHistory($row['id']);
$row['totalUsers'] = count($log);
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
static function getLatest($key) {
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE `key` = ? ORDER BY created DESC LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql, "s", array($key));
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
-
-
+
static function getLatestFromUser($users_id) {
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE `users_id` = ? ORDER BY created DESC LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql, "i", array($users_id));
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public function save() {
if (empty($this->live_servers_id)) {
$this->live_servers_id = 'NULL';
}
AVideoPlugin::onLiveStream($this->users_id, $this->live_servers_id);
return parent::save();
}
static function deleteAllFromLiveServer($live_servers_id) {
global $global;
$live_servers_id = intval($live_servers_id);
if (!empty($live_servers_id)) {
global $global;
$sql = "SELECT id FROM " . static::getTableName() . " WHERE live_servers_id = ? ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql, "i", array($live_servers_id));
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$lt = new LiveTransmitionHistory($row['id']);
$lt->delete();
}
}
}
}
public function delete() {
if (!empty($this->id)) {
LiveTransmitionHistoryLog::deleteAllFromHistory($this->id);
}
return parent::delete();
}
}
diff --git a/plugin/Live/index.php b/plugin/Live/index.php
index 21836850b..528fde9ee 100644
--- a/plugin/Live/index.php
+++ b/plugin/Live/index.php
@@ -1,300 +1,301 @@
getDataObject();
if (!empty($_GET['c'])) {
$user = User::getChannelOwner($_GET['c']);
if (!empty($user)) {
$_GET['u'] = $user['user'];
}
}
if (!empty($_GET['c'])) {
$user = User::getChannelOwner($_GET['c']);
if ($user['status'] !== 'a') {
header("Location: {$global['webSiteRootURL']}");
}
}
if (!empty($_GET['u']) && !empty($_GET['embedv2'])) {
include $global['systemRootPath'] . 'plugin/Live/view/videoEmbededV2.php';
exit;
} else if (!empty($_GET['u']) && !empty($_GET['embed'])) {
include $global['systemRootPath'] . 'plugin/Live/view/videoEmbeded.php';
exit;
} else if (!empty($_GET['u'])) {
include $global['systemRootPath'] . 'plugin/Live/view/modeYoutubeLive.php';
exit;
} else if (!User::isLogged()) {
gotToLoginAndComeBackHere("");
exit;
} else if (!User::canStream()) {
forbiddenPage(__($obj->streamDeniedMsg));
}
require_once $global['systemRootPath'] . 'objects/userGroups.php';
require_once $global['systemRootPath'] . 'objects/functions.php';
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$users_id = User::getId();
if (!empty($_GET['users_id']) && User::isAdmin()) {
$users_id = intval($_GET['users_id']);
}
// if user already have a key
$trasnmition = LiveTransmition::createTransmitionIfNeed($users_id);
+$getLiveKey = array('key'=>$trasnmition['key'], 'live_servers_id'=> Live::getLiveServersIdRequest());
if (!empty($_GET['resetKey'])) {
LiveTransmition::resetTransmitionKey($users_id);
header("Location: {$global['webSiteRootURL']}plugin/Live/");
exit;
}
$aspectRatio = "16:9";
$vjsClass = "vjs-16-9";
$trans = new LiveTransmition($trasnmition['id']);
$groups = $trans->getGroups();
//check if channel name exists
$channelName = User::getUserChannelName();
if (empty($channelName)) {
$channelName = uniqid();
$user = new User($users_id);
$user->setChannelName($channelName);
$user->save();
}
$col1Class = "col-md-12 col-lg-12";
$col2Class = "hidden";
$chat2 = AVideoPlugin::getObjectDataIfEnabled("Chat2");
if (!empty($chat2) && !empty($chat2->useStaticLayout)) {
$col1Class = "col-md-8 col-lg-8";
$col2Class = "col-md-4 col-lg-4";
}
?>
getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
useLiveServers) {
$activeServerFound = true;
?>
$value) {
$active = "";
if (isset($_REQUEST['live_servers_id'])) {
if ($_REQUEST['live_servers_id'] == $value['id']) {
$activeServerFound = true;
$active = "active";
}
} else if ($key == 0) {
$_REQUEST['live_servers_id'] = $value['id'];
$activeServerFound = true;
$active = "active";
}
?>
Edit Live Servers
getChat($trasnmition['key']);
?>
diff --git a/plugin/Live/on_publish.php b/plugin/Live/on_publish.php
index ebacdd1c8..83311eb1c 100644
--- a/plugin/Live/on_publish.php
+++ b/plugin/Live/on_publish.php
@@ -1,100 +1,114 @@
error = true;
$obj->liveTransmitionHistory_id = 0;
-_error_log("NGINX ON Publish POST: ".json_encode($_POST));
-_error_log("NGINX ON Publish GET: ".json_encode($_GET));
-_error_log("NGINX ON Publish php://input" .file_get_contents("php://input"));
+_error_log("NGINX ON Publish POST: " . json_encode($_POST));
+_error_log("NGINX ON Publish GET: " . json_encode($_GET));
+_error_log("NGINX ON Publish php://input" . file_get_contents("php://input"));
// get GET parameters
$url = $_POST['tcurl'];
if (empty($url)) {
$url = $_POST['swfurl'];
}
$parts = parse_url($url);
parse_str($parts["query"], $_GET);
-_error_log("NGINX ON Publish parse_url: ".json_encode($parts));
-_error_log("NGINX ON Publish parse_str: ".json_encode($_GET));
+_error_log("NGINX ON Publish parse_url: " . json_encode($parts));
+_error_log("NGINX ON Publish parse_str: " . json_encode($_GET));
$_GET = object_to_array($_GET);
-if($_POST['name']=='live'){
+if ($_POST['name'] == 'live') {
_error_log("NGINX ON Publish wrong name {$_POST['p']}");
// fix name for streamlab
$pParts = explode("/", $_POST['p']);
- if(!empty($pParts[1])){
+ if (!empty($pParts[1])) {
_error_log("NGINX ON Publish like key fixed");
- $_POST['name']=$pParts[1];
+ $_POST['name'] = $pParts[1];
}
}
-if(empty($_POST['name']) && !empty($_GET['name'])){
+if (empty($_POST['name']) && !empty($_GET['name'])) {
$_POST['name'] = $_GET['name'];
}
-if(empty($_POST['name']) && !empty($_GET['key'])){
+if (empty($_POST['name']) && !empty($_GET['key'])) {
$_POST['name'] = $_GET['key'];
}
-if(strpos($_GET['p'], '/') !== false){
- $parts = explode("/",$_GET['p']);
- if(!empty($parts[1])){
+if (strpos($_GET['p'], '/') !== false) {
+ $parts = explode("/", $_GET['p']);
+ if (!empty($parts[1])) {
$_GET['p'] = $parts[0];
$_POST['name'] = $parts[1];
}
}
if (!empty($_GET['p'])) {
$_GET['p'] = str_replace("/", "", $_GET['p']);
_error_log("NGINX ON Publish check if key exists ({$_POST['name']})");
$obj->row = LiveTransmition::keyExists($_POST['name']);
- _error_log("NGINX ON Publish key exists return ". json_encode($obj->row));
+ _error_log("NGINX ON Publish key exists return " . json_encode($obj->row));
if (!empty($obj->row)) {
_error_log("NGINX ON Publish new User({$obj->row['users_id']})");
$user = new User($obj->row['users_id']);
- if(!$user->thisUserCanStream()){
+ if (!$user->thisUserCanStream()) {
_error_log("NGINX ON Publish User [{$obj->row['users_id']}] can not stream");
- }else if (!empty($_GET['p']) && $_GET['p'] === $user->getPassword()) {
+ } else if (!empty($_GET['p']) && $_GET['p'] === $user->getPassword()) {
_error_log("NGINX ON Publish get LiveTransmitionHistory");
$lth = new LiveTransmitionHistory();
$lth->setTitle($obj->row['title']);
$lth->setDescription($obj->row['description']);
$lth->setKey($_POST['name']);
$lth->setUsers_id($user->getBdId());
$lth->setLive_servers_id(Live_servers::getServerIdFromRTMPHost($url));
_error_log("NGINX ON Publish saving LiveTransmitionHistory");
$obj->liveTransmitionHistory_id = $lth->save();
_error_log("NGINX ON Publish saved LiveTransmitionHistory");
$obj->error = false;
-
- } else if(empty ($_GET['p'])) {
+ } else if (empty($_GET['p'])) {
_error_log("NGINX ON Publish error, Password is empty");
} else {
- _error_log("NGINX ON Publish error, Password does not match ({$_GET['p']}) expect (".$user->getPassword().")");
+ _error_log("NGINX ON Publish error, Password does not match ({$_GET['p']}) expect (" . $user->getPassword() . ")");
}
} else {
_error_log("NGINX ON Publish error, Transmition name not found ({$_POST['name']}) ", AVideoLog::$SECURITY);
}
} else {
_error_log("NGINX ON Publish error, Password not found ", AVideoLog::$SECURITY);
}
_error_log("NGINX ON Publish deciding ...");
if (!empty($obj) && empty($obj->error)) {
_error_log("NGINX ON Publish success");
http_response_code(200);
header("HTTP/1.1 200 OK");
echo "success";
Live::on_publish($obj->liveTransmitionHistory_id);
+ ob_end_flush();
+ $lth = new LiveTransmitionHistory($obj->liveTransmitionHistory_id);
+ $m3u8 = Live::getM3U8File($lth->getKey());
+ for ($i = 5; $i > 0; $i--) {
+ if (!isURL200($m3u8)) {
+ //live is not ready request again
+ sleep($i);
+ } else {
+ break;
+ }
+ }
+ $array = setLiveKey($lth->getKey(), $lth->getLive_servers_id());
+ $array['stats'] = LiveTransmitionHistory::getStatsAndAddApplication($obj->liveTransmitionHistory_id);
+ $socketObj = sendSocketMessageToAll($array, "socketLiveONCallback");
+
exit;
} else {
_error_log("NGINX ON Publish denied ", AVideoLog::$SECURITY);
http_response_code(401);
header("HTTP/1.1 401 Unauthorized Error");
exit;
}
//_error_log(print_r($_POST, true));
//_error_log(print_r($obj, true));
//echo json_encode($obj);
\ No newline at end of file
diff --git a/plugin/Live/on_publish_done.php b/plugin/Live/on_publish_done.php
new file mode 100644
index 000000000..748663628
--- /dev/null
+++ b/plugin/Live/on_publish_done.php
@@ -0,0 +1,51 @@
+error = true;
$obj->msg = "";
$obj->streamerURL = $streamerURL;
$obj->token = $robj->token;
$obj->pid = array();
$obj->logFile = str_replace('{users_id}', $robj->users_id, $logFile);
if (empty($robj->restreamsDestinations) || !is_array($robj->restreamsDestinations)) {
$obj->msg = "There are no restreams Destinations";
error_log("Restreamer.json.php ERROR {$obj->msg}");
die(json_encode($obj));
}
error_log("Restreamer.json.php Found " . count($robj->restreamsDestinations) . " destinations: " . json_encode($robj->restreamsDestinations));
// check the token
if (empty($obj->token)) {
$obj->msg = "Token is empty";
error_log("Restreamer.json.php ERROR {$obj->msg}");
die(json_encode($obj));
}
$verifyTokenURL = "{$obj->streamerURL}plugin/Live/verifyToken.json.php?token={$obj->token}";
error_log("Restreamer.json.php verifying token {$verifyTokenURL}");
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$content = file_get_contents($verifyTokenURL, false, stream_context_create($arrContextOptions));
error_log("Restreamer.json.php verification respond content {$content}");
$json = json_decode($content);
if (empty($json)) {
$obj->msg = "Could not verify token";
error_log("Restreamer.json.php ERROR {$obj->msg} ({$verifyTokenURL}) ");
die(json_encode($obj));
} else if (!empty($json->error)) {
$obj->msg = "Token is invalid";
error_log("Restreamer.json.php ERROR {$obj->msg} ({$verifyTokenURL}) " . json_encode($json));
die(json_encode($obj));
}
error_log("Restreamer.json.php token is correct");
ignore_user_abort(true);
ob_start();
header("Connection: close");
@header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
if (empty($separateRestreams)) {
error_log("Restreamer.json.php all in one command ");
$obj->pid[] = startRestream($robj->m3u8, $robj->restreamsDestinations, $obj->logFile);
} else {
error_log("Restreamer.json.php separateRestreams " . count($robj->restreamsDestinations));
foreach ($robj->restreamsDestinations as $key => $value) {
sleep(0.5);
$obj->pid[] = startRestream($robj->m3u8, array($value), str_replace(".log", "_{$key}.log", $obj->logFile));
}
}
$obj->error = false;
error_log("Restreamer.json.php finish " . json_encode($obj));
die(json_encode($obj));
function clearCommandURL($url) {
return preg_replace('/[^0-9a-z:.\/_&?=-]/i', "", $url);
}
-function isURL200($url) {
- error_log("Restreamer.json.php checking URL {$url}");
- //open connection
- $ch = curl_init();
-
- //set the url, number of POST vars, POST data
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
- $output = curl_exec($ch);
- $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
-
- error_log("Restreamer.json.php URL {$url} return code {$httpcode}");
- return $httpcode == 200;
+if(!function_exists('isURL200')){
+ function isURL200($url) {
+ error_log("Restreamer.json.php checking URL {$url}");
+ //open connection
+ $ch = curl_init();
+
+ //set the url, number of POST vars, POST data
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+ curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
+ $output = curl_exec($ch);
+ $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ error_log("Restreamer.json.php URL {$url} return code {$httpcode}");
+ return $httpcode == 200;
+ }
}
function startRestream($m3u8, $restreamsDestinations, $logFile, $tries = 1) {
global $ffmpegBinary;
if (empty($restreamsDestinations)) {
error_log("Restreamer.json.php ERROR empty restreamsDestinations");
return false;
}
$m3u8 = clearCommandURL($m3u8);
killIfIsRunning($m3u8);
if (!isURL200($m3u8)) {
if ($tries > 10) {
error_log("Restreamer.json.php tried too many times, we could not find your stream URL");
return false;
}
error_log("Restreamer.json.php URL is not ready. trying again ({$tries})");
sleep($tries);
return startRestream($m3u8, $restreamsDestinations, $logFile, $tries + 1);
}
/*
$command = "ffmpeg -i {$m3u8} ";
foreach ($restreamsDestinations as $value) {
$value = clearCommandURL($value);
$command .= ' -max_muxing_queue_size 1024 -f flv "' . $value . '" ';
}
*
*/
if (count($restreamsDestinations) > 1) {
$command = "{$ffmpegBinary} -re -i \"{$m3u8}\" ";
foreach ($restreamsDestinations as $value) {
if(!isOpenSSLEnabled() && preg_match("/rtpms:/i", $value)){
error_log("Restreamer.json.php ERROR #1 FFMPEG openssl is not enabled, ignoring $value ");
continue;
}
$value = clearCommandURL($value);
$command .= ' -max_muxing_queue_size 1024 -acodec copy -bsf:a aac_adtstoasc -vcodec copy -f flv "' . $value . '" ';
}
} else {
if(!isOpenSSLEnabled() && preg_match("/rtpms:/i", $restreamsDestinations[0])){
error_log("Restreamer.json.php ERROR #2 FFMPEG openssl is not enabled, ignoring {$restreamsDestinations[0]} ");
}else{
$command = "ffmpeg -re -i \"{$m3u8}\" -max_muxing_queue_size 1024 -acodec copy -bsf:a aac_adtstoasc -vcodec copy -f flv \"{$restreamsDestinations[0]}\"";
}
}
if(empty($command) || !preg_match("/-f flv/i", $command)){
error_log("Restreamer.json.php ERROR command is empty ");
}else{
error_log("Restreamer.json.php startRestream {$command}, check the file ($logFile) for the log");
exec('echo \'' . $command . PHP_EOL . '\' > ' . $logFile);
exec('nohup ' . $command . ' 2>> ' . $logFile . ' > /dev/null &');
error_log("Restreamer.json.php startRestream finish");
}
return true;
}
$isOpenSSLEnabled = null;
function isOpenSSLEnabled() {
global $isOpenSSLEnabled, $ffmpegBinary;
if(isset($isOpenSSLEnabled)){
return $isOpenSSLEnabled;
}
exec("{$ffmpegBinary} 2>&1", $output, $return_var);
foreach ($output as $value) {
if (preg_match("/configuration:.*--enable-openssl/i", $value)) {
$isOpenSSLEnabled = true;
return $isOpenSSLEnabled;
}
}
$isOpenSSLEnabled = false;
return $isOpenSSLEnabled;
}
function whichffmpeg() {
exec("which ffmpeg 2>&1", $output, $return_var);
return @$output[0];
}
function getProcess($m3u8){
$m3u8 = clearCommandURL($m3u8);
global $ffmpegBinary;
exec("ps -ax 2>&1", $output, $return_var);
//error_log("Restreamer.json.php:getProcess ". json_encode($output));
foreach ($output as $value) {
$pattern = "/^([0-9]+).*".replaceSlashesForPregMatch($ffmpegBinary).".*".replaceSlashesForPregMatch($m3u8)."/i";
//error_log("Restreamer.json.php:getProcess {$pattern}");
if (preg_match($pattern, trim($value), $matches)) {
return $matches;
}
}
return false;
}
function killIfIsRunning($m3u8){
$process = getProcess($m3u8);
error_log("Restreamer.json.php killIfIsRunning checking if there is a process running for {$m3u8} ");
if(!empty($process)){
error_log("Restreamer.json.php killIfIsRunning there is a process running for {$m3u8} ". json_encode($process));
$pid = intval($process[1]);
if(!empty($pid)){
error_log("Restreamer.json.php killIfIsRunning killing {$pid} ");
exec("kill -9 {$pid} 2>&1", $output, $return_var);
sleep(1);
}
return true;
}else{
error_log("Restreamer.json.php killIfIsRunning there is not a process running for {$m3u8} ");
}
return false;
}
function replaceSlashesForPregMatch($str){
return str_replace('/', '.', $str);
}
diff --git a/plugin/Live/view/footer.php b/plugin/Live/view/footer.php
new file mode 100644
index 000000000..d1c43a572
--- /dev/null
+++ b/plugin/Live/view/footer.php
@@ -0,0 +1,32 @@
+
\ No newline at end of file
diff --git a/plugin/Live/view/menuRight.php b/plugin/Live/view/menuRight.php
index 9aea0ea07..237d35d27 100644
--- a/plugin/Live/view/menuRight.php
+++ b/plugin/Live/view/menuRight.php
@@ -1,310 +1,352 @@
doNotShowGoLiveButton) && User::canStream()) {
?>
" data-placement="bottom" >
0
diff --git a/plugin/Live/view/modeYoutubeLive.php b/plugin/Live/view/modeYoutubeLive.php
index fb8081b3f..d534ae110 100644
--- a/plugin/Live/view/modeYoutubeLive.php
+++ b/plugin/Live/view/modeYoutubeLive.php
@@ -1,230 +1,231 @@
$livet['key'], 'live_servers_id'=> Live::getLiveServersIdRequest());
$lt = new LiveTransmition($livet['id']);
if (!$lt->userCanSeeTransmition()) {
forbiddenPage("You are not allowed see this streaming");
}
$uuid = LiveTransmition::keyNameFix($livet['key']);
$u = new User(0, $_GET['u'], false);
$user_id = $u->getBdId();
$video['users_id'] = $user_id;
$subscribe = Subscribe::getButton($user_id);
$name = $u->getNameIdentificationBd();
$name = "{$name} " . User::getEmailVerifiedIcon($user_id) . " ";
$liveTitle = $livet['title'];
$liveDescription = $livet['description'];
$liveImg = User::getPhoto($user_id);
if (!empty($_REQUEST['playlists_id_live'])) {
$liveTitle = PlayLists::getNameOrSerieTitle($_REQUEST['playlists_id_live']);
$liveDescription = PlayLists::getDescriptionIfIsSerie($_REQUEST['playlists_id_live']);
$liveImg = PlayLists::getImage($_REQUEST['playlists_id_live']);
}
$video['creator'] = '';
$img = "{$global['webSiteRootURL']}plugin/Live/getImage.php?u={$_GET['u']}&format=jpg";
$imgw = 640;
$imgh = 360;
$liveDO = AVideoPlugin::getObjectData("Live");
$video['type'] = 'video';
AVideoPlugin::getModeYouTubeLive($user_id);
$isCompressed = AVideoPlugin::loadPluginIfEnabled('TheaterButton') && TheaterButton::isCompressed();
$sideAd = getAdsSideRectangle();
$modeYoutubeBottomClass1 = "col-sm-7 col-md-7 col-lg-6";
$modeYoutubeBottomClass2 = "col-sm-5 col-md-5 col-lg-4 ";
if (empty($sideAd) && !AVideoPlugin::loadPluginIfEnabled("Chat2")) {
$modeYoutubeBottomClass1 = "col-sm-12 col-md-12 col-lg-10";
$modeYoutubeBottomClass2 = "hidden ";
}
?>
getPageTitleSeparator() . __("Live") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
- getWebSiteTitle(); ?>" />
" />
isAPrivateLive()) {
?>
disableShareAndPlaylist) && empty($advancedCustom->disableShareOnly)) { ?>
disableShareAndPlaylist) && empty($advancedCustom->disableShareOnly)) {
getShareMenu($liveTitle, $link, $link, addQueryStringParameter($link, 'embed', 1), $img,"row bgWhite list-group-item menusDiv");
}
?>
diff --git a/plugin/Live/view/onlineLabel.php b/plugin/Live/view/onlineLabel.php
index a091f6ef3..03505393f 100644
--- a/plugin/Live/view/onlineLabel.php
+++ b/plugin/Live/view/onlineLabel.php
@@ -1,166 +1,169 @@
ONLINE";
+}else{
+ echo "OFFLINE ";
+}
+
?>
-OFFLINE
+
\ No newline at end of file
diff --git a/plugin/Live/view/onlineUsers.php b/plugin/Live/view/onlineUsers.php
index f68bc252c..c46276038 100644
--- a/plugin/Live/view/onlineUsers.php
+++ b/plugin/Live/view/onlineUsers.php
@@ -1,20 +1,22 @@
doNotDisplayCounter) {
return false;
}
if (empty($lu->doNotDisplayLiveCounter)) {
+ $liveUsersOnlineClass = "liveUsersOnline_{$streamName} liveUsersOnline_{$streamName}_".Live::getAvailableLiveServer();
?>
- " data-placement="bottom" > 0
+ " data-placement="bottom" > 0
doNotDisplayTotal)) {
+ $liveUsersViewsClass = "liveUsersViews_{$streamName} liveUsersViews_{$streamName}_".Live::getAvailableLiveServer();
?>
- " data-placement="bottom" > 0
+ " data-placement="bottom" > 0
\ No newline at end of file
diff --git a/plugin/Live/view/videoEmbeded.php b/plugin/Live/view/videoEmbeded.php
index 87ec7b702..34ebcd104 100644
--- a/plugin/Live/view/videoEmbeded.php
+++ b/plugin/Live/view/videoEmbeded.php
@@ -1,123 +1,124 @@
$livet['key'], 'live_servers_id'=> Live::getLiveServersIdRequest());
$uuid = LiveTransmition::keyNameFix($livet['key']);
$p = AVideoPlugin::loadPlugin("Live");
$objSecure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory');
if (!empty($objSecure)) {
$objSecure->verifyEmbedSecurity();
}
$u = new User(0, $_GET['u'], false);
$user_id = $u->getBdId();
$video['users_id'] = $user_id;
AVideoPlugin::getModeYouTubeLive($user_id);
$_REQUEST['live_servers_id'] = Live::getLiveServersIdRequest();
$poster = Live::getPosterImage($livet['users_id'], $_REQUEST['live_servers_id']);
?>
getWebSiteTitle(); ?>
diff --git a/plugin/Live/view/videoEmbededV2.php b/plugin/Live/view/videoEmbededV2.php
index 54389f5be..78b055276 100644
--- a/plugin/Live/view/videoEmbededV2.php
+++ b/plugin/Live/view/videoEmbededV2.php
@@ -1,156 +1,157 @@
$livet['key'], 'live_servers_id'=> Live::getLiveServersIdRequest());
$uuid = LiveTransmition::keyNameFix($livet['key']);
$p = AVideoPlugin::loadPlugin("Live");
$objSecure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory');
if(!empty($objSecure)){
$objSecure->verifyEmbedSecurity();
}
$u = new User(0, $_GET['u'], false);
$user_id = $u->getBdId();
$video['users_id'] = $user_id;
AVideoPlugin::getModeYouTubeLive($user_id);
$_REQUEST['live_servers_id'] = Live::getLiveServersIdRequest();
$poster = Live::getPosterImage($livet['users_id'], $_REQUEST['live_servers_id']);
?>
getWebSiteTitle(); ?>
diff --git a/plugin/LiveLinks/LiveLinks.php b/plugin/LiveLinks/LiveLinks.php
index 5a525bee5..2aee852cb 100644
--- a/plugin/LiveLinks/LiveLinks.php
+++ b/plugin/LiveLinks/LiveLinks.php
@@ -1,374 +1,375 @@
isReadyLabel(array('Live'));
$help = " Help ";
return $desc.$help;
}
public function getName() {
return "LiveLinks";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->onlyAdminCanAddLinks = true;
$obj->buttonTitle = "Add a Live Link";
$obj->disableGifThumbs = false;
$obj->disableLiveThumbs = false;
$obj->doNotShowLiveLinksLabel = false;
$obj->disableProxy = false;
return $obj;
}
public function getUUID() {
return "39d3b5fe-9702-4f1d-9ffd-fe1cd22a4dc7";
}
public function getPluginVersion() {
return "3.1";
}
public function canAddLinks() {
$obj = $this->getDataObject();
if (!User::isLogged()) {
return false;
}
if ($obj->onlyAdminCanAddLinks && !User::isAdmin()) {
return false;
}
return User::canStream();
}
public function getHTMLMenuRight() {
global $global;
$obj = $this->getDataObject();
if (!$this->canAddLinks()) {
return '';
}
include $global['systemRootPath'] . 'plugin/LiveLinks/view/menuRight.php';
}
static function getAllActive() {
global $global;
$sql = "SELECT * FROM LiveLinks WHERE status='a' AND start_date <= now() AND end_date >= now() ORDER BY start_date ";
$res = $global['mysqli']->query($sql);
$rows = array();
if ($res) {
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
static function getImage($id) {
global $global;
return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format=jpg";
}
static function getImageGif($id) {
global $global;
return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format=gif";
}
/**
*
* @return type array(array("key"=>'live key', "users"=>false, "name"=>$userName, "user"=>$user, "photo"=>$photo, "UserPhoto"=>$UserPhoto, "title"=>''));
*/
public function getLiveApplicationArray() {
global $global;
$obj = $this->getDataObject();
$filename = $global['systemRootPath'] . 'plugin/LiveLinks/view/menuItem.html';
$filenameExtra = $global['systemRootPath'] . 'plugin/LiveLinks/view/extraItem.html';
$filenameExtraVideoPage = $global['systemRootPath'] . 'plugin/LiveLinks/view/extraItemVideoPage.html';
$row = LiveLinks::getAllActive();
$array = array();
$search = array(
'_unique_id_',
'_user_photo_',
'_title_',
'_user_identification_',
'_description_',
'_link_',
'_imgJPG_',
'_imgGIF_',
'_class_'
);
$content = file_get_contents($filename);
$contentExtra = file_get_contents($filenameExtra);
$contentExtraVideoPage = file_get_contents($filenameExtraVideoPage);
if(empty($_GET['requestComesFromVideoPage'])){
$regex = "/".addcslashes($global['webSiteRootURL'],"/")."video\/.*/";
$requestComesFromVideoPage = preg_match($regex, @$_SERVER["HTTP_REFERER"]);
}else{
$requestComesFromVideoPage = 1;
}
foreach ($row as $value) {
if($value['type']=='unlisted'){
continue;
}
if($value['type']=='logged_only'){
if(!User::isLogged()){
continue;
}
}
$UserPhoto = User::getPhoto($value['users_id']);
$name = User::getNameIdentificationById($value['users_id']);
$replace = array(
$value['id'],
$UserPhoto,
$value['title'],
$name,
str_replace('"', "", $value['description']),
self::getLink($value['id']),
' ',
empty($obj->disableGifThumbs)?(' '):"",
($requestComesFromVideoPage)?"col-xs-6":"col-lg-2 col-md-4 col-sm-4 col-xs-6"
);
$newContent = str_replace($search, $replace, $content);
$newContentExtra = str_replace($search, $replace, $contentExtra);
$newContentExtraVideoPage = str_replace($search, $replace, $contentExtraVideoPage);
$array[] = array(
"type" => "LiveLink",
"html" => $newContent,
"htmlExtra" => $newContentExtra,
"htmlExtraVideoPage" => $newContentExtraVideoPage,
"UserPhoto" => $UserPhoto,
"title" => $value['title'],
"name" => $name,
"poster" => self::getPosterToLiveFromId($value['id']),
"link" => self::getLinkToLiveFromId($value['id'], true)
);
}
return $array;
}
public function updateScript() {
global $global;
if (AVideoPlugin::compareVersion($this->getName(), "2") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/LiveLinks/install/updateV2.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
if (AVideoPlugin::compareVersion($this->getName(), "3.1") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/LiveLinks/install/updateV3.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
return true;
}
public function getHeadCode() {
global $global;
$obj = $this->getDataObject();
// preload image
$js = "";
$css = '';
if(!empty($obj->doNotShowLiveLinksLabel)){
$css .= '';
}
return $js.$css;
}
public function getLinkToLiveFromId($id, $embed=false){
return self::getLink($id, $embed);
}
public static function getLink($id, $embed=false){
global $global;
//return "{$global['webSiteRootURL']}plugin/LiveLinks/view/Live.php?link={$id}".($embed?"&embed=1":"");
$ll = new LiveLinksTable($id);
if(!$embed){
return "{$global['webSiteRootURL']}liveLink/{$id}/". urlencode(cleanURLName($ll->getTitle()));
}else{
return "{$global['webSiteRootURL']}liveLinkEmbed/{$id}/". urlencode(cleanURLName($ll->getTitle()));
}
}
public function getPosterToLiveFromId($id){
global $global;
return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format=jpg";
}
public static function isLiveThumbsDisabled(){
$obj = AVideoPlugin::getDataObject("LiveLinks");
if(!empty($obj->disableLiveThumbs)){
return true;
}
return false;
}
public function getPosterThumbsImage($users_id, $live_servers_id) {
global $global;
$file = Live::_getPosterThumbsImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = "plugin/Live/view/OnAir.jpg";
}
return $file;
}
public function getUploadMenuButton() {
global $global;
if (!$this->canAddLinks()) {
return '';
}
$obj = $this->getDataObject();
$buttonTitle = $obj->buttonTitle;
//include $global['systemRootPath'] . 'plugin/LiveLinks/getUploadMenuButton.php';
}
public static function getAllVideos($status = "", $showOnlyLoggedUserVideos = false, $activeUsersOnly = true) {
global $global, $config, $advancedCustom;
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$status = str_replace("'", "", $status);
$sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified "
. " FROM LiveLinks as v "
. " LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$uid = intval(User::getId());
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$uid = intval($showOnlyLoggedUserVideos);
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
if ($status == "publicOnly") {
$sql .= " AND v.`type` = 1 ";
} elseif (!empty($status)) {
$sql .= " AND v.`type` = '{$status}'";
}
if (!empty($_GET['catName'])) {
- $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
+ $catName = $global['mysqli']->real_escape_string($_GET['catName']);
+ $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))";
}
if (!empty($_GET['modified'])) {
$_GET['modified'] = str_replace("'", "", $_GET['modified']);
$sql .= " AND v.modified >= '{$_GET['modified']}'";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if (strpos(strtolower($sql), 'limit') === false) {
if (!empty($_GET['limitOnceToOne'])) {
$sql .= " LIMIT 1";
unset($_GET['limitOnceToOne']);
}else{
$_REQUEST['rowCount'] = getRowCount();
if (!empty($_REQUEST['rowCount'])) {
$sql .= " LIMIT {$_REQUEST['rowCount']}";
} else {
_error_log("getAllVideos without limit " . json_encode(debug_backtrace()));
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = 100;
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
}
}
//echo $sql;exit;
//_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$videos = array();
if ($res != false) {
foreach ($fullData as $row) {
unset($row['password']);
unset($row['recoverPass']);
if (empty($otherInfo)) {
$otherInfo = array();
$otherInfo['category'] = xss_esc_back($row['category']);
$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']);
//$otherInfo['title'] = UTF8encode($row['title']);
$otherInfo['description'] = UTF8encode($row['description']);
$otherInfo['descriptionHTML'] = Video::htmlDescription($otherInfo['description']);
$otherInfo['filesize'] = 0;
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['rotation'] = 0;
$row['filename'] = '';
$row['type'] = 'livelinks';
$row['duration'] = '';
$row['isWatchLater'] = 0;
$row['isFavorite'] = 0;
$row['views_count'] = 0;
$videos[] = $row;
}
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
}
diff --git a/plugin/Plugin.abstract.php b/plugin/Plugin.abstract.php
index a6743b492..d60510dfe 100644
--- a/plugin/Plugin.abstract.php
+++ b/plugin/Plugin.abstract.php
@@ -1,537 +1,545 @@
getUUID();
if (empty(PluginAbstract::$dataObject[$uuid])) {
$obj = Plugin::getPluginByUUID($uuid);
//echo $obj['object_data'];
$o = array();
if (!empty($obj['object_data'])) {
$o = json_decode(stripslashes($obj['object_data']));
$json_last_error = json_last_error();
if ($json_last_error !== JSON_ERROR_NONE) {
//var_dump($this->getName(), $json_last_error, $o, $obj['object_data']);
//_error_log('getDataObject - JSON error (' . $json_last_error . ') ' . $this->getName()." ".$this->getUUID());
$o = json_decode($obj['object_data']);
$json_last_error = json_last_error();
}
switch ($json_last_error) {
case JSON_ERROR_NONE:
//echo ' - No errors';
break;
default:
_error_log('getDataObject - JSON error ' . $this->getName());
_error_log($obj['object_data']);
_error_log('striped slashes');
_error_log(stripslashes($obj['object_data']));
case JSON_ERROR_DEPTH:
_error_log(' - Maximum stack depth exceeded');
break;
case JSON_ERROR_STATE_MISMATCH:
_error_log(' - Underflow or the modes mismatch');
break;
case JSON_ERROR_CTRL_CHAR:
_error_log(' - Unexpected control character found');
break;
case JSON_ERROR_SYNTAX:
_error_log(' - Syntax error, malformed JSON');
_error_log($obj['object_data']);
_error_log('striped slashes');
_error_log(stripslashes($obj['object_data']));
break;
case JSON_ERROR_UTF8:
_error_log(' - Malformed UTF-8 characters, possibly incorrectly encoded');
break;
}
}
$eo = $this->getEmptyDataObject();
$wholeObjects = array_merge((array) $eo, (array) $o);
$disabledPlugins = plugin::getAllDisabled();
foreach ($disabledPlugins as $value) {
$p = AVideoPlugin::loadPlugin($value['dirName']);
if (is_object($p)) {
$foreginObjects = $p->getCustomizeAdvancedOptions();
if ($foreginObjects) {
foreach ($foreginObjects as $optionName => $defaultValue)
if (isset($wholeObjects[$optionName]))
unset($wholeObjects[$optionName]);
}
}
}
PluginAbstract::$dataObject[$this->getUUID()] = $wholeObjects;
}else {
$wholeObjects = PluginAbstract::$dataObject[$this->getUUID()];
}
//var_dump($obj['object_data']);
//var_dump($eo, $o, (object) array_merge((array) $eo, (array) $o));exit;
return (object) $wholeObjects;
}
public function setDataObject($object) {
$pluginRow = Plugin::getPluginByUUID($this->getUUID());
if(empty($pluginRow)){
return false;
}
$obj = new Plugin($pluginRow['id']);
$obj->setObject_data(addcslashes(json_encode($object), '\\'));
return $obj->save();
}
public function setDataObjectParameter($parameterName, $value) {
$object = $this->getDataObject();
eval("\$object->$parameterName = \$value;");
return $this->setDataObject($object);
}
public function getEmptyDataObject() {
$obj = new stdClass();
return $obj;
}
public function getFirstPage() {
return false;
}
public function afterNewVideo($videos_id) {
return false;
}
public function afterDonation($from_users_id, $how_much, $videos_id, $users_id) {
return false;
}
public function afterNewComment($comments_id) {
return false;
}
public function afterNewResponse($comments_id) {
return false;
}
public function xsendfilePreVideoPlay() {
return false;
}
public function getLogin() {
$obj = new stdClass();
$obj->class = ""; // btn btn-primary btn-block
$obj->icon = ""; // fab fa-facebook-square
$obj->type = ""; // Facebook, Google, etc
$obj->linkToDevelopersPage = ""; //https://console.developers.google.com/apis/credentials , https://developers.facebook.com/apps
return $obj;
}
public function getWatchActionButton($videos_id) {
return "";
}
public function getNetflixActionButton($videos_id) {
return "";
}
public function getGalleryActionButton($videos_id) {
return "";
}
public function getStart() {
return false;
}
public function getEnd() {
return false;
}
public function afterVideoJS() {
return false;
}
public function canEditPlugin() {
global $global;
return empty($global['disableAdvancedConfigurations']);
}
public function hidePlugin() {
return false;
}
public function getChannelButton() {
return "";
}
public function getVideoManagerButton() {
return "";
}
public function getLivePanel() {
return "";
}
public function getPlayListButtons($playlist_id) {
return "";
}
public function getMyAccount($users_id) {
return "";
}
/**
*
* @return type array(array("key"=>'live key', "users"=>false, "name"=>$userName, "user"=>$user, "photo"=>$photo, "UserPhoto"=>$UserPhoto, "title"=>''));
*/
public function getLiveApplicationArray() {
return array();
}
public function addRoutes() {
return false;
}
public function addView($videos_id, $total) {
return false;
}
public function getCustomizeAdvancedOptions() {
return false;
}
public function getUserOptions() {
return array();
}
public function getModeYouTube($videos_id) {
return false;
}
public function getModeYouTubeLive($users_id) {
return false;
}
public function getEmbed($videos_id) {
return false;
}
/**
* Loads a channel before display the channel page, usefull to create customized channel pages
* @param type $user is an database array from channels owner
* @return boolean
*/
public function getChannel($user_id, $user) {
return false;
}
/**
*
* @return type return a list of IDs of the user groups
*/
public function getDynamicUserGroupsId($users_id) {
return array();
}
public function navBarButtons() {
return "";
}
public function navBarProfileButtons() {
return "";
}
public function navBar() {
return "";
}
public function isReady($pluginsList) {
$return = array('ready' => array(), 'missing' => array());
foreach ($pluginsList as $name) {
$plugin = AVideoPlugin::loadPlugin($name);
$uuid = $plugin->getUUID();
if (!AVideoPlugin::isEnabled($uuid)) {
$return['missing'][] = array('name' => $name, 'uuid' => $uuid);
} else {
$return['ready'][] = array('name' => $name, 'uuid' => $uuid);
}
}
return $return;
}
public function isReadyLabel($pluginsList) {
$desc = " ";
$ready = $this->isReady($pluginsList);
foreach ($ready['ready'] as $value) {
$desc .= "{$value['name']} ";
}
foreach ($ready['missing'] as $value) {
$desc .= "{$value['name']} ";
}
return $desc;
}
public function getAllVideosExcludeVideosIDArray() {
return array();
}
/**
*
* @param type $users_id
* @return 0 = I dont know, -1 = can not upload, 1 = can upload
*/
public function userCanUpload($users_id) {
return 0;
}
/**
*
* @param type $users_id
* @param type $videos_id
* @return 0 = I dont know, -1 = can not watch, 1 = can watch
*/
public function userCanWatchVideo($users_id, $videos_id) {
return 0;
}
/**
*
* @param type $users_id
* @param type $videos_id
* @return 0 = I dont know, -1 = can not watch, 1 = can watch
*/
public function userCanWatchVideoWithAds($users_id, $videos_id) {
return 0;
}
/**
* temporary, to avoid error on old secureVideosDirectory plugins
* @return boolean
*/
function verifyEmbedSecurity() {
return true;
}
function showAds($videos_id) {
return true;
}
function getVideo() {
return null;
}
public function onUserSignIn($users_id) {
return null;
}
public function onUserSignup($users_id) {
return null;
}
public function onLiveStream($users_id, $live_servers_id) {
return null;
}
public function thumbsOverlay($videos_id) {
return "";
}
public static function profileTabName($users_id) {
return "";
}
public static function profileTabContent($users_id) {
return "";
}
public static function getVideoWhereClause() {
return "";
}
public static function getManagerVideosAddNew() {
return "";
}
public static function saveVideosAddNew($post, $videos_id) {
return true;
}
public static function getManagerVideosReset() {
return "";
}
public static function getManagerVideosEdit() {
return "";
}
public static function getManagerVideosEditField() {
return "";
}
public static function getManagerVideosJavaScripts() {
return "";
}
public static function getManagerVideosTab() {
return "";
}
public static function getManagerVideosBody() {
return "";
}
public static function getAllVideosArray($videos_id) {
return array();
}
public static function getVideoTags($videos_id) {
return array();
}
public function getMobileInfo() {
return null;
}
public function getUploadMenuButton() {
return "";
}
public function dataSetup() {
return "";
}
function getPermissionsOptions(){
return array();
}
protected function addDataObjectHelper($property, $name, $description=""){
$this->dataObjectHelper[$property] = array("name"=>$name, "description"=>$description);
}
function getDataObjectHelper(){
return $this->dataObjectHelper;
}
+
+ function onUserSocketConnect($users_id, $data){
+
+ }
+
+ function onUserSocketDisconnect($users_id, $data){
+
+ }
}
class PluginPermissionOption{
private $type, $name, $description, $className;
function __construct($type, $name, $description, $className) {
$this->type = $type;
$this->name = $name;
$this->description = $description;
$this->className = $className;
}
function getType() {
return $this->type;
}
function getName() {
return $this->name;
}
function getDescription() {
return $this->description;
}
function getClassName() {
return $this->className;
}
}
\ No newline at end of file
diff --git a/plugin/Socket/Message.php b/plugin/Socket/Message.php
index 56df5e086..3e52a1f42 100644
--- a/plugin/Socket/Message.php
+++ b/plugin/Socket/Message.php
@@ -1,152 +1,429 @@
clients = new \SplObjectStorage;
$this->clients = [];
_log_message("Construct");
}
public function onOpen(ConnectionInterface $conn) {
- _log_message("New connection! ({$conn->resourceId})");
+ global $onMessageSentTo;
+ $onMessageSentTo = array();
+ $query = $conn->httpRequest->getUri()->getQuery();
+ parse_str($query, $wsocketToken);
+ if (empty($wsocketToken['webSocketToken'])) {
+ _log_message("Empty websocket token ");
+ return false;
+ }
+ $json = getDecryptedInfo($wsocketToken['webSocketToken']);
+ if (empty($json)) {
+ _log_message("Invalid websocket token ");
+ return false;
+ }
// Store the new connection to send messages to later
//$this->clients->attach($conn);
if (!isset($this->clients[$conn->resourceId])) {
$this->clients[$conn->resourceId] = array();
}
$this->clients[$conn->resourceId]['conn'] = $conn;
+ $this->clients[$conn->resourceId]['users_id'] = $json->from_users_id;
+ $this->clients[$conn->resourceId]['yptDeviceId'] = $json->yptDeviceId;
+ $this->clients[$conn->resourceId]['selfURI'] = $json->selfURI;
+ $this->clients[$conn->resourceId]['isCommandLine'] = $wsocketToken['isCommandLine'];
+ $this->clients[$conn->resourceId]['videos_id'] = $json->videos_id;
+ $this->clients[$conn->resourceId]['live_key'] = object_to_array(@$json->live_key);
+ $this->clients[$conn->resourceId]['autoEvalCodeOnHTML'] = $json->autoEvalCodeOnHTML;
+ $this->clients[$conn->resourceId]['ip'] = $json->ip;
+ $this->clients[$conn->resourceId]['location'] = $json->location;
- self::msgToResourceId("Connection opened", $conn->resourceId);
- }
-
- public function msgToResourceId($msg, $resourceId) {
- if(!is_array($msg)){
- $this->msgToArray($msg);
+ _log_message("New connection ");
+ if ($this->shouldPropagateInfo($this->clients[$conn->resourceId])) {
+ _log_message("shouldPropagateInfo ");
+ $this->msgToAll($conn, array(), \SocketMessageType::NEW_CONNECTION, true);
+ \AVideoPlugin::onUserSocketConnect($json->from_users_id, $this->clients[$conn->resourceId]);
+ } else {
+ _log_message("NOT shouldPropagateInfo ");
}
- $msg['ResourceId'] = $resourceId;
- $msg = json_encode($msg);
- _log_message("msgToUser: resourceId=({$resourceId}) {$msg}");
- $this->clients[$resourceId]['conn']->send($msg);
- }
-
- public function msgToUsers_id($msg, $users_id) {
- if(empty($users_id)){
- return false;
+ if (!empty($json->videos_id)) {
+ _log_message("msgToAllSameVideo ");
+ $this->msgToAllSameVideo($json->videos_id, "");
+ } else {
+ _log_message("NOT msgToAllSameVideo ");
}
- $this->clients[$from->resourceId]['users_id'];
- $count = 0;
- foreach ($this->clients as $resourceId => $value) {
- if($value['users_id'] == $users_id){
- $count++;
- $this->msgToResourceId($msg, $resourceId);
- }
+ if (!empty($json->live_key)) {
+ _log_message("msgToAllSameLive ");
+ $this->msgToAllSameLive($json->live_key, "");
+ } else {
+ _log_message("NOT msgToAllSameLive ");
}
- _log_message("msgToUsers_id: sent to ($count) clients users_id={$users_id}");
-
}
- public function msgToAll(ConnectionInterface $from, $msg) {
- _log_message("msgToAll");
- $numRecv = count($this->clients) - 1;
- //_log_message(sprintf('Connection %d sending message "%s" to %d other connection%s' . PHP_EOL , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'));
-
- foreach ($this->clients as $key => $client) {
- if ($from !== $client['conn']) {
- $this->msgToResourceId($msg, $key);
- }
+ public function onClose(ConnectionInterface $conn) {
+ global $onMessageSentTo;
+ $onMessageSentTo = array();
+
+ unset($getStatsLive);
+ unset($_getStats);
+ _log_message("Connection {$conn->resourceId} has disconnected");
+ // The connection is closed, remove it, as we can no longer send it messages
+ //$this->clients->detach($conn);
+ $users_id = $this->clients[$conn->resourceId]['users_id'];
+ $videos_id = $this->clients[$conn->resourceId]['videos_id'];
+ $live_key = $this->clients[$conn->resourceId]['live_key'];
+ if ($this->shouldPropagateInfo($this->clients[$conn->resourceId])) {
+ $this->msgToAll($conn, array(), \SocketMessageType::NEW_DISCONNECTION, true);
+ \AVideoPlugin::onUserSocketDisconnect($users_id, $this->clients[$conn->resourceId]);
+ }
+
+ unset($this->clients[$conn->resourceId]);
+ if (!empty($videos_id)) {
+ $this->msgToAllSameVideo($videos_id, "");
+ }
+ if (!empty($live_key)) {
+ $this->msgToAllSameLive($live_key, "");
}
}
public function onMessage(ConnectionInterface $from, $msg) {
- _log_message("onMessage: {$msg}");
+ global $onMessageSentTo;
+ $onMessageSentTo = array();
+ //_log_message("onMessage: {$msg}");
$json = json_decode($msg);
if (empty($json)) {
_log_message("onMessage ERROR: JSON is empty ");
return false;
}
if (empty($json->webSocketToken)) {
_log_message("onMessage ERROR: webSocketToken is empty ");
return false;
}
+
if (!$msgObj = getDecryptedInfo($json->webSocketToken)) {
_log_message("onMessage ERROR: could not decrypt webSocketToken");
return false;
}
switch ($json->msg) {
case "webSocketToken":
if (empty($this->clients[$from->resourceId]['users_id'])) {
- _log_message("onMessage: set users_id {$msgObj->users_id}");
- $this->clients[$from->resourceId]['users_id'] = $msgObj->users_id;
+ _log_message("onMessage:webSocketToken");
+ $this->clients[$from->resourceId]['users_id'] = $msgObj->from_users_id;
+ $this->clients[$from->resourceId]['yptDeviceId'] = $msgObj->yptDeviceId;
}
break;
default:
$this->msgToArray($json);
- if (!empty($json['to_users_id'])) {
- $this->msgToUsers_id($json['msg'], $json['to_users_id']);
+ _log_message("onMessage:msgObj: " . json_encode($json));
+ if (!empty($msgObj->send_to_uri_pattern)) {
+ $this->msgToSelfURI($json, $msgObj->send_to_uri_pattern);
+ } else if (!empty($json['to_users_id'])) {
+ $this->msgToUsers_id($json, $json['to_users_id']);
} else {
- $this->msgToAll($from, $json['msg']);
+ $this->msgToAll($from, $json);
}
break;
}
}
+
+ private function shouldPropagateInfo($connection) {
+ if ($connection['yptDeviceId'] == 'unknowDevice') {
+ return false;
+ }
+ if (!empty($connection['isCommandLine'])) {
+ return false;
+ }
+ return true;
+ }
+
+ public function msgToResourceId($msg, $resourceId, $type = "") {
+ global $onMessageSentTo;
+ if (in_array($resourceId, $onMessageSentTo)) {
+ return false;
+ }
+ // do not sent duplicated messages
+ $onMessageSentTo[] = $resourceId;
+
+ if (!is_array($msg)) {
+ $this->msgToArray($msg);
+ }
+ if(!empty($msg['webSocketToken'])){
+ unset($msg['webSocketToken']);
+ }
+ if (empty($type)) {
+ $type = \SocketMessageType::DEFAULT_MESSAGE;
+ }
+
+ $videos_id = $this->clients[$resourceId]['videos_id'];
+ $users_id = $this->clients[$resourceId]['users_id'];
+ $live_key = $this->clients[$resourceId]['live_key'];
+
+ $obj = array();
+ $obj['ResourceId'] = $resourceId;
+ $obj['type'] = $type;
+
+ if(isset($msg['callback'])){
+ $obj['callback'] = $msg['callback'];
+ unset($msg['callback']);
+ }else{
+ $obj['callback'] = "";
+ }
+
+ if(!empty($msg['json'])){
+ $obj['msg'] = $msg['json'];
+ }else if(!empty($msg['msg'])){
+ $obj['msg'] = $msg['msg'];
+ }else{
+ $obj['msg'] = $msg;
+ }
+
+ $obj['uniqid'] = uniqid();
+ $obj['users_id'] = $users_id;
+ $obj['videos_id'] = $videos_id;
+ $obj['live_key'] = $live_key;
+ $obj['autoUpdateOnHTML'] = array(
+ 'socket_users_id' => $users_id,
+ 'socket_resourceId' => $resourceId,
+ 'total_devices_online' => count($this->clients),
+ 'total_users_online' => count($this->getUsersIdFromDevicesOnline()),
+ 'usersonline_per_video' => $this->getTotalPerVideo(),
+ 'total_on_same_video' => $this->getTotalOnVideos_id($videos_id),
+ 'total_on_same_live' => $this->getTotalOnlineOnLive_key($live_key)
+ );
+ $obj['autoEvalCodeOnHTML'] = $this->clients[$resourceId]['autoEvalCodeOnHTML'];
+
+ $msgToSend = json_encode($obj);
+ _log_message("msgToResourceId: resourceId=({$resourceId})");
+ $this->clients[$resourceId]['conn']->send($msgToSend);
+ }
+
+ public function msgToUsers_id($msg, $users_id, $type = "") {
+ if (empty($users_id)) {
+ return false;
+ }
+ $count = 0;
+ foreach ($this->clients as $resourceId => $value) {
+ if ($value['users_id'] == $users_id) {
+ $count++;
+ $this->msgToResourceId($msg, $resourceId, $type);
+ }
+ }
+ _log_message("msgToUsers_id: sent to ($count) clients users_id={$users_id}");
+ }
+
+ public function msgToSelfURI($msg, $pattern, $type = "") {
+ if (empty($pattern)) {
+ return false;
+ }
+ $count = 0;
+ foreach ($this->clients as $resourceId => $value) {
+ if (empty($value['selfURI'])) {
+ continue;
+ }
+ if (preg_match($pattern, $value['selfURI'])) {
+ $count++;
+ $this->msgToResourceId($msg, $resourceId, $type);
+ }
+ }
+ _log_message("msgToSelfURI: sent to ($count) clients pattern={$pattern} ");
+ }
+
+ public function getTotalSelfURI($pattern) {
+ if (empty($videos_id)) {
+ return false;
+ }
+ $count = 0;
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['selfURI'])) {
+ continue;
+ }
+ if (preg_match($pattern, $client['selfURI'])) {
+ $count++;
+ }
+ }
+ _log_message("getTotalSelfURI: total ($count) clients pattern={$pattern} ");
+ return $count;
+ }
+
+ public function getTotalPerVideo() {
+ $videos = array();
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['videos_id'])) {
+ continue;
+ }
+ if (!isset($videos[$client['videos_id']])) {
+ $videos[$client['videos_id']] = array('videos_id' => $client['videos_id'], 'total' => 1);
+ } else {
+ $videos[$client['videos_id']]['total']++;
+ }
+ }
+ return $videos;
+ }
+
+ public function msgToDevice_id($msg, $yptDeviceId) {
+ if (empty($yptDeviceId)) {
+ return false;
+ }
+ $count = 0;
+ foreach ($this->clients as $resourceId => $value) {
+ if ($value['yptDeviceId'] == $yptDeviceId) {
+ $count++;
+ $this->msgToResourceId($msg, $resourceId);
+ }
+ }
+ _log_message("msgToDevice_id: sent to ($count) clients yptDeviceId={$yptDeviceId}");
+ }
+
+ public function getUsersIdFromDevicesOnline() {
+ $users_id = array();
+ foreach ($this->clients as $value) {
+ if (empty($value['yptDeviceId']) || empty($value['users_id'])) {
+ continue;
+ }
+ if(in_array($value['users_id'], $users_id)){
+ continue;
+ }
+ if ($this->shouldPropagateInfo($value)) {
+ $users_id[] = $value['users_id'];
+ }
+ }
+ return $users_id;
+ }
+
+ public function msgToAll(ConnectionInterface $from, $msg, $type = "", $includeMe = false) {
+ _log_message("msgToAll {$type}");
+ foreach ($this->clients as $key => $client) {
+ if (!empty($includeMe) || $from !== $client['conn']) {
+ $this->msgToResourceId($msg, $key, $type);
+ }
+ }
+ }
+
+ public function getTotalOnVideos_id($videos_id) {
+ if (empty($videos_id)) {
+ return false;
+ }
+ //_log_message("getTotalOnVideos_id: {$videos_id}");
+ $count = 0;
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['videos_id'])) {
+ continue;
+ }
+ if ($client['videos_id'] == $videos_id) {
+ $count++;
+ }
+ }
+ return $count;
+ }
- private function msgToArray(&$json){
+
+ public function getTotalOnlineOnLive_key($live_key) {
+ if (empty($live_key)) {
+ return false;
+ }
+
+ $live_key = object_to_array($live_key);
+ //_log_message("getTotalOnlineOnLive_key: key={$live_key['key']} live_servers_id={$live_key['live_servers_id']}");
+ $count = 0;
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['live_key'])) {
+ continue;
+ }
+ if ($client['live_key']['key'] == $live_key['key'] && $client['live_key']['live_servers_id'] == $live_key['live_servers_id']) {
+ $count++;
+ }
+ }
+
+ return $count;
+ }
+
+ public function msgToAllSameVideo($videos_id, $msg) {
+ if (empty($videos_id)) {
+ return false;
+ }
+ if (!is_array($msg)) {
+ $this->msgToArray($msg);
+ }
+ $msg['total'] = $this->getTotalOnVideos_id($videos_id);
+ $msg['videos_id'] = $videos_id;
+ _log_message("msgToAllSameVideo: {$videos_id}");
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['videos_id'])) {
+ continue;
+ }
+ if ($client['videos_id'] == $videos_id) {
+ $this->msgToResourceId($msg, $key, \SocketMessageType::ON_VIDEO_MSG);
+ }
+ }
+ }
+
+ public function msgToAllSameLive($live_key, $msg) {
+ if (empty($live_key)) {
+ return false;
+ }
+ $live_key = object_to_array($live_key);
+ if (!is_array($msg)) {
+ $this->msgToArray($msg);
+ }
+ _mysql_connect();
+ $msg['is_live'] = \Live::isLiveAndIsReadyFromKey($live_key['key'], $live_key['live_servers_id'], true);
+ _mysql_close();
+ _log_message("msgToAllSameLive: key={$live_key['key']} live_servers_id={$live_key['live_servers_id']}");
+ foreach ($this->clients as $key => $client) {
+ if (empty($client['live_key'])) {
+ continue;
+ }
+ if ($client['live_key']['key'] == $live_key['key'] && $client['live_key']['live_servers_id'] == $live_key['live_servers_id']) {
+ $this->msgToResourceId($msg, $key, \SocketMessageType::ON_LIVE_MSG);
+ }
+ }
+ }
+
+ private function msgToArray(&$json) {
$json = $this->makeSureIsArray($json);
- $msg = $this->makeSureIsArray(@$json['msg']);
- $msg['callback'] = @$json['callback'];
- $msg['uniqid'] = uniqid();
- $json['msg'] = $msg;
return true;
}
-
- private function makeSureIsArray($msg){
- if(empty($msg)){
+
+ private function makeSureIsArray($msg) {
+ if (empty($msg)) {
return array();
}
- if(is_string($msg)){
+ if (is_string($msg)) {
$decoded = json_decode($msg);
- }else{
+ } else {
$decoded = object_to_array($msg);
}
- if(is_string($msg) && !$decoded){
+ if (is_string($msg) && !$decoded) {
return array($msg);
- }else if(is_string($msg)){
+ } else if (is_string($msg)) {
return object_to_array($decoded);
}
return object_to_array($msg);
}
- public function onClose(ConnectionInterface $conn) {
- _log_message("Connection {$conn->resourceId} has disconnected");
- // The connection is closed, remove it, as we can no longer send it messages
- //$this->clients->detach($conn);
- unset($this->clients[$conn->resourceId]);
- }
-
public function onError(ConnectionInterface $conn, \Exception $e) {
_log_message("An error has occurred: {$e->getMessage()}");
$conn->close();
}
public function getTags() {
return array('free', 'live');
}
}
function _log_message($msg) {
- _error_log($msg);
+ _error_log($msg, \AVideoLog::$SOCKET);
echo $msg . PHP_EOL;
}
diff --git a/plugin/Socket/Socket.php b/plugin/Socket/Socket.php
index 439b192d1..e627b4e08 100644
--- a/plugin/Socket/Socket.php
+++ b/plugin/Socket/Socket.php
@@ -1,115 +1,150 @@
";
+ $desc .= "nohup php {$global['systemRootPath']}plugin/Socket/server.php &";
//$desc .= $this->isReadyLabel(array('YPTWallet'));
return $desc;
}
public function getName() {
return "Socket";
}
public function getUUID() {
return "Socket-5ee8405eaaa16";
}
public function getPluginVersion() {
return "1.0";
}
public function updateScript() {
global $global;
/*
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql');
}
*
*/
return true;
}
public function getEmptyDataObject() {
+ global $global;
$obj = new stdClass();
+
+ $host = parse_url($global['webSiteRootURL'], PHP_URL_HOST);
+ $server_crt_file = "/etc/letsencrypt/live/{$host}/fullchain.pem";
+ $server_key_file = "/etc/letsencrypt/live/{$host}/privkey.pem";
+
+ if(!file_exists($server_crt_file)){
+ $server_crt_file = "";
+ }
+ if(!file_exists($server_key_file)){
+ $server_key_file = "";
+ }
+
$obj->port = "8888";
- /*
- $obj->textSample = "text";
- $obj->checkboxSample = true;
- $obj->numberSample = 5;
-
- $o = new stdClass();
- $o->type = array(0=>__("Default"))+array(1,2,3);
- $o->value = 0;
- $obj->selectBoxSample = $o;
-
- $o = new stdClass();
- $o->type = "textarea";
- $o->value = "";
- $obj->textareaSample = $o;
- */
+ self::addDataObjectHelper('port', 'Server Port', 'You also MUST open this port on the firewall');
+ $obj->debugSocket = false;
+ self::addDataObjectHelper('debugSocket', 'Show server debugger to admin', 'This will show a panel with some socket informations to the ADMIN user only');
+ $obj->debugAllUsersSocket = false;
+ self::addDataObjectHelper('debugAllUsersSocket', 'Show server debugger to all', 'Same as above but will show the panel to all users');
+ $obj->server_crt_file = $server_crt_file;
+ self::addDataObjectHelper('server_crt_file', 'SSL Certificate File', 'If your site use HTTPS, you MUST provide one');
+ $obj->server_key_file = $server_key_file;
+ self::addDataObjectHelper('server_key_file', 'SSL Certificate Key File', 'If your site use HTTPS, you MUST provide one');
+ $obj->allow_self_signed = true;
+ self::addDataObjectHelper('allow_self_signed', 'Allow self signed certs', 'Should be unchecked in production');
+
return $obj;
}
public function getFooterCode() {
self::getSocketJS();
}
-
+
public static function getSocketJS() {
global $global;
- $socketobj = AVideoPlugin::getDataObject("Socket");
- $address = parse_url($global['webSiteRootURL'], PHP_URL_HOST);
- $port = $socketobj->port;
include $global['systemRootPath'] . 'plugin/Socket/footer.php';
}
- public static function send($msg, $callbackJSFunction="", $users_id="") {
- global $global, $SocketSendObj;
- $socketobj = AVideoPlugin::getDataObject("Socket");
- $address = "localhost";
- $port = $socketobj->port;
-
+ public static function send($msg, $callbackJSFunction = "", $users_id = "", $send_to_uri_pattern = "") {
+ global $global, $SocketSendObj, $SocketSendUsers_id, $SocketSendResponseObj;
if(!is_string($msg)){
$msg = json_encode($msg);
}
+ $SocketSendUsers_id = $users_id;
+ if(!is_array($SocketSendUsers_id)){
+ $SocketSendUsers_id = array($SocketSendUsers_id);
+ }
$SocketSendObj = new stdClass();
- $SocketSendObj->webSocketToken = getEncryptedInfo();
+ $SocketSendObj->webSocketToken = getEncryptedInfo(0,$send_to_uri_pattern);
$SocketSendObj->msg = $msg;
$SocketSendObj->json = json_decode($msg);
- $SocketSendObj->to_users_id = $users_id;
$SocketSendObj->callback = $callbackJSFunction;
- $obj = new stdClass();
- $obj->error = true;
- $obj->msg = "";
- $obj->msgObj = $SocketSendObj;
- $obj->callbackJSFunction = $callbackJSFunction;
-
-
+ $SocketSendResponseObj = new stdClass();
+ $SocketSendResponseObj->error = true;
+ $SocketSendResponseObj->msg = "";
+ $SocketSendResponseObj->msgObj = $SocketSendObj;
+ $SocketSendResponseObj->callbackJSFunction = $callbackJSFunction;
require_once $global['systemRootPath'] . 'objects/autoload.php';
- \Ratchet\Client\connect("ws://{$address}:{$port}")->then(function($conn) {
- global $SocketSendObj;
+ \Ratchet\Client\connect(self::getWebSocketURL(true, true))->then(function($conn) {
+ global $SocketSendObj, $SocketSendUsers_id, $SocketSendResponseObj;
$conn->on('message', function($msg) use ($conn) {
//echo "Received: {$msg}\n";
- $conn->close();
+ //$conn->close();
+ $SocketSendResponseObj->error = false;
});
- $conn->send(json_encode($SocketSendObj));
+ foreach ($SocketSendUsers_id as $users_id) {
+ $SocketSendObj->to_users_id = $users_id;
+ $conn->send(json_encode($SocketSendObj));
+ }
+
+ $conn->close();
+
+ //$SocketSendResponseObj->error = false;
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
- return $obj;
+ return $SocketSendResponseObj;
+ }
+
+ public static function getWebSocketURL($useLocalHost = true, $isCommandLine=false) {
+ global $global;
+ $socketobj = AVideoPlugin::getDataObject("Socket");
+ $address = "localhost";
+ if (empty($useLocalHost)) {
+ $address = parse_url($global['webSiteRootURL'], PHP_URL_HOST);
+ }
+ $port = $socketobj->port;
+ $protocol = "ws";
+ $scheme = parse_url($global['webSiteRootURL'], PHP_URL_SCHEME);
+ if(strtolower($scheme)==='https'){
+ $protocol = "wss";
+ }
+ return "{$protocol}://{$address}:{$port}?webSocketToken=".getEncryptedInfo(0)."&isCommandLine=".intval($isCommandLine);
}
-
}
diff --git a/plugin/Socket/crontab.php b/plugin/Socket/crontab.php
new file mode 100644
index 000000000..cd939d2a0
--- /dev/null
+++ b/plugin/Socket/crontab.php
@@ -0,0 +1,7 @@
+debugAllUsersSocket) || (User::isAdmin() && !empty($obj->debugSocket))) {
+ ?>
+
+
+
+ users_id 0
+ ResourceId 0
+ Total Devices Online 0
+ Total Users Online 0
+ onlineOnThisVideo 0
+ onlineOnThisLive 0
+
+
+
diff --git a/plugin/Socket/functions.php b/plugin/Socket/functions.php
index 8cd9ab400..a489a8956 100644
--- a/plugin/Socket/functions.php
+++ b/plugin/Socket/functions.php
@@ -1,25 +1,87 @@
users_id = User::getId();
- $msgObj->token = getToken(43200); // valid for 12 hours
+ $msgObj->from_users_id = User::getId();
+ $msgObj->yptDeviceId = getDeviceID();
+ $msgObj->token = getToken($timeOut);
$msgObj->time = time();
-
+ $msgObj->selfURI = getSelfURI();
+ $msgObj->ip = getRealIpAddr();
+ $msgObj->send_to_uri_pattern = $send_to_uri_pattern;
+ $msgObj->autoEvalCodeOnHTML = array();
+ if (empty($msgObj->videos_id)) {
+ $msgObj->videos_id = getVideos_id();
+ }
+ if (empty($msgObj->live_key)) {
+ $msgObj->live_key = isLive();
+ }
+
+ if(AVideoPlugin::isEnabledByName('User_location')){
+ $msgObj->location = User_Location::getThisUserLocation();
+ }else{
+ $msgObj->location = false;
+ }
+
+ /*
+ if (!empty($msgObj->live_key)) {
+ $msgObj->is_live = Live::isLiveAndIsReadyFromKey($msgObj->live_key['key'], $msgObj->live_key['live_servers_id'], true);
+ if($msgObj->is_live){
+ $code = "onlineLabelOnline('.liveOnlineLabel');";
+ }else{
+ $code = "onlineLabelOffline('.liveOnlineLabel');";
+ }
+ $msgObj->autoEvalCodeOnHTML[] = $code;
+ }
+ *
+ */
+
return encryptString(json_encode($msgObj));
}
function getDecryptedInfo($string) {
$decriptedString = decryptString($string);
$json = json_decode($decriptedString);
if (!empty($json) && !empty($json->token)) {
if (isTokenValid($json->token)) {
return $json;
} else {
_error_log("socket:getDecryptedInfo: token is invalid ");
}
} else {
_error_log("socket:getDecryptedInfo: json->token is empty ({$decriptedString})");
}
return false;
}
+
+class SocketMessageType {
+
+ const NEW_CONNECTION = "NEW_CONNECTION";
+ const NEW_DISCONNECTION = "NEW_DISCONNECTION";
+ const DEFAULT_MESSAGE = "DEFAULT_MESSAGE";
+ const ON_VIDEO_MSG = "ON_VIDEO_MSG";
+ const ON_LIVE_MSG = "ON_LIVE_MSG";
+
+}
+
+function getTotalViewsLive_key($live_key) {
+ if (empty($live_key)) {
+ return false;
+ }
+ $live_key = object_to_array($live_key);
+ _mysql_connect();
+ $liveUsersEnabled = \AVideoPlugin::isEnabledByName("LiveUsers");
+ if ($liveUsersEnabled) {
+ $liveUsers = new \LiveOnlineUsers(0);
+ $total = $liveUsers->getTotalUsersFromTransmitionKey($live_key['key'], $live_key['live_servers_id']);
+ } else {
+ $total = null;
+ }
+
+ _mysql_close();
+
+ return $total;
+}
diff --git a/plugin/Socket/script.js b/plugin/Socket/script.js
index df1b213b7..f3370da4b 100644
--- a/plugin/Socket/script.js
+++ b/plugin/Socket/script.js
@@ -1,94 +1,115 @@
-var socketMyResourceId = 0;
var socketConnectRequested = 0;
+var totalDevicesOnline = 0;
function socketConnect() {
- if(socketConnectRequested){
+ if (socketConnectRequested) {
return false;
}
socketConnectRequested = 1;
- console.log('Trying to reconnect on ' + webSocketURL);
+ console.log('Trying to reconnect on socket...');
conn = new WebSocket(webSocketURL);
conn.onopen = function (e) {
- console.log("Socket onopen", e);
- socketMyResourceId = 0;
- sendSocketMessageToNone("webSocketToken", "");
+ console.log("Socket onopen");
return false;
};
conn.onmessage = function (e) {
- //console.log("Socket onmessage", e);
var json = JSON.parse(e.data);
- console.log("Socket onmessage", json);
- if (!socketMyResourceId) {
- socketMyResourceId = parseInt(json.ResourceId);
- var msg = "Socket socketMyResourceId " + socketMyResourceId;
- //sendSocketMessage(msg, "", "");
- console.log(msg);
+ parseSocketResponse(json);
+ if (json.type == webSocketTypes.ON_VIDEO_MSG) {
+ console.log("Socket onmessage ON_VIDEO_MSG", json);
+ $('.videoUsersOnline, .videoUsersOnline_' + json.videos_id).text(json.total);
+ }
+ if (json.type == webSocketTypes.ON_LIVE_MSG) {
+ console.log("Socket onmessage ON_LIVE_MSG", json);
+ var selector = '#liveViewStatusID_' + json.live_key.key + '_' + json.live_key.live_servers_id;
+ if (json.is_live) {
+ onlineLabelOnline(selector);
+ } else {
+ onlineLabelOffline(selector);
+ }
+ }
+ if (json.type == webSocketTypes.NEW_CONNECTION) {
+ //console.log("Socket onmessage NEW_CONNECTION", json);
+ } else if (json.type == webSocketTypes.NEW_DISCONNECTION) {
+ //console.log("Socket onmessage NEW_DISCONNECTION", json);
} else {
var myfunc;
if (json.callback) {
+ console.log("Socket onmessage json.callback", json.callback);
var code = "if(typeof " + json.callback + " == 'function'){myfunc = " + json.callback + ";}else{myfunc = defaultCallback;}";
//console.log(code);
eval(code);
} else {
- console.log("onmessage: callback not found");
+ console.log("onmessage: callback not found", json);
myfunc = defaultCallback;
}
- myfunc(json);
+ myfunc(json.msg);
}
-
};
conn.onclose = function (e) {
socketConnectRequested = 0;
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function () {
socketConnect();
}, 1000);
};
conn.onerror = function (err) {
socketConnectRequested = 0;
console.error('Socket encountered error: ', err.message, 'Closing socket');
conn.close();
};
}
function sendSocketMessageToAll(msg, callback) {
sendSocketMessageToUser(msg, callback, "");
}
function sendSocketMessageToNone(msg, callback) {
sendSocketMessageToUser(msg, callback, -1);
}
-function sendSocketMessageToUser(msg, callback, users_id) {
+function sendSocketMessageToUser(msg, callback, to_users_id) {
if (conn.readyState === 1) {
- conn.send(JSON.stringify({msg: msg, webSocketToken: webSocketToken, callback: callback, users_id, users_id}));
+ conn.send(JSON.stringify({msg: msg, webSocketToken: webSocketToken, callback: callback, to_users_id: to_users_id}));
} else {
console.log('Socket not ready send message in 1 second');
setTimeout(function () {
- sendSocketMessageToUser(msg, callback, to_users_id);
+ sendSocketMessageToUser(msg, to_users_id, callback);
}, 1000);
}
}
-function sendSocketMessageToUser(msg, users_id, callback) {
- if (conn.readyState === 1) {
- conn.send(JSON.stringify({msg: msg, webSocketToken: webSocketToken, users_id: users_id, callback: callback}));
- } else {
- console.log('Socket not ready send message in 1 second');
- setTimeout(function () {
- sendSocketMessageToUser(msg, users_id, callback);
- }, 1000);
- }
-}
-
-function isSocketActive(){
+function isSocketActive() {
return typeof conn != 'undefined' && conn.readyState === 1;
}
function defaultCallback(json) {
//console.log('defaultCallback', json);
}
+function parseSocketResponse(json) {
+ console.log("parseSocketResponse", json);
+ if (json && typeof json.autoUpdateOnHTML !== 'undefined') {
+ //console.log("parseSocketResponse", json.autoUpdateOnHTML);
+ for (var prop in json.autoUpdateOnHTML) {
+ if(json.autoUpdateOnHTML[prop]===false){
+ continue;
+ }
+ $('.'+prop).text(json.autoUpdateOnHTML[prop]);
+ }
+ }
+
+ if (json && typeof json.autoEvalCodeOnHTML !== 'undefined') {
+ for (var prop in json.autoEvalCodeOnHTML) {
+ if(json.autoEvalCodeOnHTML[prop]===false){
+ continue;
+ }
+ //console.log("autoEvalCodeOnHTML", json.autoEvalCodeOnHTML[prop]);
+ eval(json.autoEvalCodeOnHTML[prop]);
+ }
+ }
+}
+
$(function () {
socketConnect();
});
\ No newline at end of file
diff --git a/plugin/Socket/send.json.php b/plugin/Socket/send.json.php
index a83c26555..fabeeb7d5 100644
--- a/plugin/Socket/send.json.php
+++ b/plugin/Socket/send.json.php
@@ -1,23 +1,27 @@
error = true;
$obj->msg = "";
if(empty($_REQUEST['msg'])){
$obj->msg = "The message is empty";
die(json_encode($obj));
}
if(!AVideoPlugin::isEnabledByName("Socket")){
$obj->msg = "Socket plugin not enabled";
die(json_encode($obj));
}
$obj = sendSocketMessage($_REQUEST['msg']);
die(json_encode($obj));
\ No newline at end of file
diff --git a/plugin/Socket/server.php b/plugin/Socket/server.php
index 837710c86..a9bf5c033 100644
--- a/plugin/Socket/server.php
+++ b/plugin/Socket/server.php
@@ -1,28 +1,59 @@
port}");
-$server = IoServer::factory(
- new HttpServer(
- new WsServer(
- new Message()
- )
- ),
- $obj->port
-);
-$server->run();
\ No newline at end of file
+$scheme = parse_url($global['webSiteRootURL'], PHP_URL_SCHEME);
+if(strtolower($scheme)!=='https'){
+ $server = IoServer::factory(
+ new HttpServer(
+ new WsServer(
+ new Message()
+ )
+ ),
+ $obj->port
+ );
+
+ $server->run();
+} else {
+ $parameters = [
+ 'local_cert' => $obj->server_crt_file,
+ 'local_pk' => $obj->server_key_file,
+ 'allow_self_signed' => $obj->allow_self_signed, // Allow self signed certs (should be false in production)
+ 'verify_peer' => false
+ ];
+
+ echo "Server Parameters ".json_encode($parameters).PHP_EOL;
+ echo "Starting server on port {$obj->port}".PHP_EOL;
+
+ $loop = React\EventLoop\Factory::create();
+// Set up our WebSocket server for clients wanting real-time updates
+ $webSock = new React\Socket\Server('0.0.0.0:' . $obj->port, $loop);
+ $webSock = new React\Socket\SecureServer($webSock, $loop, $parameters);
+ $webServer = new Ratchet\Server\IoServer(
+ new HttpServer(
+ new WsServer(
+ new Message()
+ )
+ ),
+ $webSock
+ );
+
+ $loop->run();
+}
\ No newline at end of file
diff --git a/plugin/Socket/start.json.php b/plugin/Socket/start.json.php
new file mode 100644
index 000000000..29bb90284
--- /dev/null
+++ b/plugin/Socket/start.json.php
@@ -0,0 +1,30 @@
+error = true;
+$obj->msg = "";
+$obj->pid = "none";
+$obj->time = time();
+
+
+$videosDir = getVideosDir();
+$pidFile = "{$videosDir}socketPID.log";
+
+if(file_exists($pidFile)){
+ $oldObj = json_decode(file_get_contents($pidFile));
+ if(!empty($oldObj)){
+ killProcess($oldObj->pid);
+ }
+}
+
+$obj->pid = execAsync("php '{$global['systemRootPath']}plugin/Socket/server.php'");
+
+file_put_contents($pidFile, json_encode($obj));
+
+die(json_encode($obj));
\ No newline at end of file
diff --git a/view/channelProgram.php b/view/channelProgram.php
index c2b50ee18..748533d2f 100644
--- a/view/channelProgram.php
+++ b/view/channelProgram.php
@@ -1,604 +1,613 @@
getUsers_id();
}
$user_id = $_GET['user_id'];
$publicOnly = true;
$isMyChannel = false;
if (User::isLogged() && $user_id == User::getId()) {
$publicOnly = false;
$isMyChannel = true;
}
$programs = PlayList::getAllFromUser($user_id, $publicOnly, false, @$_GET['program_id']);
if (empty($programs)) {
$programs = PlayList::getAllFromUser($user_id, $publicOnly);
} else {
$videosArrayId = PlayList::getVideosIdFromPlaylist($_GET['program_id']);
$videos_id = $videosArrayId[0];
}
$playListsObj = AVideoPlugin::getObjectData("PlayLists");
?>
getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
$program) {
@$timesC[__LINE__] += microtime(true) - $startC;
$startC = microtime(true);
$videosArrayId = PlayList::getVideosIdFromPlaylist($program['id']);
@$timesC[__LINE__] += microtime(true) - $startC;
$startC = microtime(true);
//getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true)
if (empty($videosArrayId) && ($program['status'] == "favorite" || $program['status'] == "watch_later")) {
unset($programs[$key]);
continue;
} else if (empty($videosArrayId)) {
$videosP = array();
} else if ($advancedCustom->AsyncJobs) {
$videosP = Video::getAllVideosAsync("viewable", false, true, $videosArrayId, false, true);
} else {
$videosP = Video::getAllVideos("viewable", false, true, $videosArrayId, false, true);
}//var_dump($videosArrayId, $videosP);exit;
@$timesC[__LINE__] += microtime(true) - $startC;
$startC = microtime(true);
//_error_log("channelPlaylist videosP: ".json_encode($videosP));
$videosP = PlayList::sortVideos($videosP, $videosArrayId);
@$timesC[__LINE__] += microtime(true) - $startC;
$startC = microtime(true);
//_error_log("channelPlaylist videosP2: ".json_encode($videosP));
//_error_log("channelPlaylist videosArrayId: ".json_encode($videosArrayId));
$playListButtons = AVideoPlugin::getPlayListButtons($program['id']);
@$timesC[__LINE__] += microtime(true) - $startC;
$startC = microtime(true);
?>
plugin/PlayLists/embed.php?playlists_id=" frameborder="0" allowfullscreen="allowfullscreen" allow="autoplay">'/>
thumbsGif;
$poster = $images->thumbsJpg;
$class = "";
$style = "";
if ($count > 6) {
$class = "showMoreLess{$program['id']}";
$style = "display: none;";
}
?>
label === __("Group")) {
?>
text; ?>
doNotDisplayViews)) {
?>
';
+ }
+ if($count%3===0){
+ echo '
';
+ }
+ if($count%2===0){
+ echo '
';
+ }
}
?>
\ No newline at end of file
diff --git a/view/include/footer.php b/view/include/footer.php
index 41484750f..be7039d34 100644
--- a/view/include/footer.php
+++ b/view/include/footer.php
@@ -1,178 +1,181 @@
" . __('You have a new version to install') . "',
showHideTransition: 'plain',
icon: 'error',
hideAfter: 20000
});";
}
+/*
if ($version = thereIsAnyRemoteUpdate()) {
$footerjs .= "$.toast({
heading: 'Update available',
text: '" . __('Our repository is now running at version') . " " . $version->version . " ',
showHideTransition: 'plain',
icon: 'warning',
hideAfter: 20000
});";
}
+ *
+ */
if (empty($advancedCustom)) {
$advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced");
}
?>
getFooter();
}
if (empty($custom)) {
?>
EnableWavesurfer;
}
if ((($video['type'] == "audio") || ($video['type'] == "linkAudio")) && ($waveSurferEnabled)) {
$jsFiles[] = "view/js/videojs-wavesurfer/wavesurfer.min.js";
$jsFiles[] = "view/js/videojs-wavesurfer/dist/videojs.wavesurfer.min.js";
}
}
$jsFiles = array_merge($jsFiles, AVideoPlugin::getJSFiles());
$jsURL = combineFiles($jsFiles, "js");
?>
";
}
if (!empty($advancedCustom->footerHTMLCode->value)) {
echo $advancedCustom->footerHTMLCode->value;
}
?>
\ No newline at end of file
diff --git a/view/include/navbar.php b/view/include/navbar.php
index b7d98ce24..d97943deb 100644
--- a/view/include/navbar.php
+++ b/view/include/navbar.php
@@ -1,1393 +1,1394 @@
" class="btn btn-default" style="position: absolute; right: 10px; top: 5px;">
body{padding-top:0;}';
}
echo ' ';
return '';
}
if (!empty($advancedCustomUser->keepViewerOnChannel)) {
if (!empty($_GET['channelName'])) {
_session_start();
$_SESSION['channelName'] = $_GET['channelName'];
}
if (!empty($_GET['leaveChannel'])) {
_session_start();
unset($_SESSION['channelName']);
}
}
session_write_close();
global $includeDefaultNavBar, $global, $config, $advancedCustom, $advancedCustomUser;
if (!isset($global['systemRootPath'])) {
require_once '../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/category.php';
$_GET['parentsOnly'] = "1";
if (empty($_SESSION['language'])) {
$lang = 'us';
} else {
$lang = $_SESSION['language'];
}
$thisScriptFile = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if (empty($sidebarStyle)) {
$sidebarStyle = "display: none;";
}
$includeDefaultNavBar = true;
AVideoPlugin::navBar();
if (!$includeDefaultNavBar) {
return false;
}
?>
userMustBeLoggedIn) && !empty($advancedCustomUser->userMustBeLoggedInCloseButtonURL)) {
?>
userMustBeLoggedIn) && empty($advancedCustom->disableNavbar)) || $thisScriptFile["basename"] === "signUp.php" || $thisScriptFile["basename"] === "userRecoverPass.php") || User::isLogged()) {
$updateFiles = getUpdatesFilesArray();
?>
keepViewerOnChannel) && !empty($_SESSION['channelName'])) {
$user = User::getChannelOwner($_SESSION['channelName']);
?>
underMenuBarHTMLCode->value)) {
echo $advancedCustom->underMenuBarHTMLCode->value;
}
} else if ($thisScriptFile["basename"] !== 'user.php' && empty($advancedCustom->disableNavbar)) {
}
unset($_GET['parentsOnly']);
?>
diff --git a/view/js/script.js b/view/js/script.js
index 495a35d59..e29683241 100644
--- a/view/js/script.js
+++ b/view/js/script.js
@@ -1,1173 +1,1183 @@
var modal;
var player;
var floatLeft = "";
var floatTop = "";
var floatWidth = "";
var floatHeight = "";
var changingVideoFloat = 0;
var floatClosed = 0;
var fullDuration = 0;
var isPlayingAd = false;
var mainVideoHeight = 0;
var mouseX;
var mouseY;
var videoContainerDragged = false;
var youTubeMenuIsOpened = false;
var userIsControling = false;
$(document).mousemove(function (e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
String.prototype.stripAccents = function () {
var returnvar = this.replace(/[áàâãªä]/g, 'a');
returnvar = returnvar.replace(/[ÁÀÂÃÄ]/g, 'A');
returnvar = returnvar.replace(/[ÍÌÎÏ]/g, 'I');
returnvar = returnvar.replace(/[íìîï]/g, 'i');
returnvar = returnvar.replace(/[éèêë]/g, 'e');
returnvar = returnvar.replace(/[ÉÈÊË]/g, 'E');
returnvar = returnvar.replace(/[óòôõºö]/g, 'o');
returnvar = returnvar.replace(/[ÓÒÔÕÖ]/g, 'O');
returnvar = returnvar.replace(/[úùûü]/g, 'u');
returnvar = returnvar.replace(/[ÚÙÛÜ]/g, 'U');
returnvar = returnvar.replace(/ç/g, 'c');
returnvar = returnvar.replace(/Ç/g, 'C');
returnvar = returnvar.replace(/ñ/g, 'n');
returnvar = returnvar.replace(/Ñ/g, 'N');
returnvar = returnvar.replace(/–/g, '-');
returnvar = returnvar.replace(/[’‘‹›‚]/g, ' ');
returnvar = returnvar.replace(/[“”«»„]/g, ' ');
returnvar = returnvar.replace(/ /g, ' ');
returnvar = returnvar.replace(/Є/g, 'YE');
returnvar = returnvar.replace(/І/g, 'I');
returnvar = returnvar.replace(/Ѓ/g, 'G');
returnvar = returnvar.replace(/і/g, 'i');
returnvar = returnvar.replace(/№/g, '#');
returnvar = returnvar.replace(/є/g, 'ye');
returnvar = returnvar.replace(/ѓ/g, 'g');
returnvar = returnvar.replace(/А/g, 'A');
returnvar = returnvar.replace(/Б/g, 'B');
returnvar = returnvar.replace(/В/g, 'V');
returnvar = returnvar.replace(/Г/g, 'G');
returnvar = returnvar.replace(/Д/g, 'D');
returnvar = returnvar.replace(/Е/g, 'E');
returnvar = returnvar.replace(/Ё/g, 'YO');
returnvar = returnvar.replace(/Ж/g, 'ZH');
returnvar = returnvar.replace(/З/g, 'Z');
returnvar = returnvar.replace(/И/g, 'I');
returnvar = returnvar.replace(/Й/g, 'J');
returnvar = returnvar.replace(/К/g, 'K');
returnvar = returnvar.replace(/Л/g, 'L');
returnvar = returnvar.replace(/М/g, 'M');
returnvar = returnvar.replace(/Н/g, 'N');
returnvar = returnvar.replace(/О/g, 'O');
returnvar = returnvar.replace(/П/g, 'P');
returnvar = returnvar.replace(/Р/g, 'R');
returnvar = returnvar.replace(/С/g, 'S');
returnvar = returnvar.replace(/Т/g, 'T');
returnvar = returnvar.replace(/У/g, 'U');
returnvar = returnvar.replace(/Ф/g, 'F');
returnvar = returnvar.replace(/Х/g, 'H');
returnvar = returnvar.replace(/Ц/g, 'C');
returnvar = returnvar.replace(/Ч/g, 'CH');
returnvar = returnvar.replace(/Ш/g, 'SH');
returnvar = returnvar.replace(/Щ/g, 'SHH');
returnvar = returnvar.replace(/Ъ/g, '');
returnvar = returnvar.replace(/Ы/g, 'Y');
returnvar = returnvar.replace(/Ь/g, '');
returnvar = returnvar.replace(/Э/g, 'E');
returnvar = returnvar.replace(/Ю/g, 'YU');
returnvar = returnvar.replace(/Я/g, 'YA');
returnvar = returnvar.replace(/а/g, 'a');
returnvar = returnvar.replace(/б/g, 'b');
returnvar = returnvar.replace(/в/g, 'v');
returnvar = returnvar.replace(/г/g, 'g');
returnvar = returnvar.replace(/д/g, 'd');
returnvar = returnvar.replace(/е/g, 'e');
returnvar = returnvar.replace(/ё/g, 'yo');
returnvar = returnvar.replace(/ж/g, 'zh');
returnvar = returnvar.replace(/з/g, 'z');
returnvar = returnvar.replace(/и/g, 'i');
returnvar = returnvar.replace(/й/g, 'j');
returnvar = returnvar.replace(/к/g, 'k');
returnvar = returnvar.replace(/л/g, 'l');
returnvar = returnvar.replace(/м/g, 'm');
returnvar = returnvar.replace(/н/g, 'n');
returnvar = returnvar.replace(/о/g, 'o');
returnvar = returnvar.replace(/п/g, 'p');
returnvar = returnvar.replace(/р/g, 'r');
returnvar = returnvar.replace(/с/g, 's');
returnvar = returnvar.replace(/т/g, 't');
returnvar = returnvar.replace(/у/g, 'u');
returnvar = returnvar.replace(/ф/g, 'f');
returnvar = returnvar.replace(/х/g, 'h');
returnvar = returnvar.replace(/ц/g, 'c');
returnvar = returnvar.replace(/ч/g, 'ch');
returnvar = returnvar.replace(/ш/g, 'sh');
returnvar = returnvar.replace(/щ/g, 'shh');
returnvar = returnvar.replace(/ъ/g, '');
returnvar = returnvar.replace(/ы/g, 'y');
returnvar = returnvar.replace(/ь/g, '');
returnvar = returnvar.replace(/э/g, 'e');
returnvar = returnvar.replace(/ю/g, 'yu');
returnvar = returnvar.replace(/я/g, 'ya');
returnvar = returnvar.replace(/—/g, '-');
returnvar = returnvar.replace(/«/g, '');
returnvar = returnvar.replace(/»/g, '');
returnvar = returnvar.replace(/…/g, '');
return returnvar;
};
function clean_name(str) {
str = str.stripAccents().toLowerCase();
return str.replace(/[!#$&'()*+,/:;=?@[\] ]+/g, "-");
}
function lazyImage() {
try {
if ($(".thumbsJPG").length) {
$('.thumbsJPG').lazy({
effect: 'fadeIn',
visibleOnly: true,
// called after an element was successfully handled
afterLoad: function (element) {
element.removeClass('blur');
var gif = element.parent().find('.thumbsGIF');
gif.lazy({
effect: 'fadeIn'
});
setTimeout(function () {
gif.hide();
gif.height(element.height());
gif.width(element.width());
}, 100);
}
});
mouseEffect();
}
} catch (e) {
}
}
lazyImage();
var pleaseWaitIsINUse = false;
function setPlayerListners() {
if (typeof player !== 'undefined') {
player.on('pause', function () {
clearTimeout(promisePlayTimeout);
console.log("setPlayerListners: pause");
//userIsControling = true;
});
player.on('play', function () {
clearTimeout(promisePlayTimeout);
console.log("setPlayerListners: play");
//userIsControling = true;
});
$("#mainVideo .vjs-mute-control").click(function () {
Cookies.set('muted', player.muted(), {
path: '/',
expires: 365
});
});
} else {
setTimeout(function () {
setPlayerListners();
}, 2000);
}
}
function removeTracks() {
var oldTracks = player.remoteTextTracks();
var i = oldTracks.length;
while (i--) {
player.removeRemoteTextTrack(oldTracks[i]);
}
}
function changeVideoSrc(vid_obj, source) {
var srcs = [];
removeTracks();
for (i = 0; i < source.length; i++) {
if (source[i].type) {
console.log(source[i].type);
if (source[i].type === "application/x-mpegURL") {
// it is HLS cancel it
return false;
}
srcs.push(source[i]);
} else if (source[i].srclang) {
player.addRemoteTextTrack(source[i]);
}
}
vid_obj.src(srcs);
setTimeout(function () {
changeVideoSrcLoad();
}, 1000);
return true;
}
function changeVideoSrcLoad() {
console.log("changeVideoSrcLoad: Try to load player");
player.load();
player.ready(function () {
console.log("changeVideoSrcLoad: Player ready");
var err = this.error();
if (err && err.code) {
console.log("changeVideoSrcLoad: Load player Error");
setTimeout(function () {
changeVideoSrcLoad();
}, 1000);
} else {
console.log("changeVideoSrcLoad: Load player Success, Play");
setTimeout(function () {
player.load();
console.log("changeVideoSrcLoad: Trying to play");
player.play();
}, 1000);
}
});
}
/**
*
* @param {String} str 00:00:00
* @returns {int} int of seconds
*/
function strToSeconds(str) {
var partsOfStr = str.split(':');
var seconds = parseInt(partsOfStr[2]);
seconds += parseInt(partsOfStr[1]) * 60;
seconds += parseInt(partsOfStr[0]) * 60 * 60;
return seconds;
}
/**
*
* @param {int} seconds
* @param {int} level 3 = 00:00:00 2 = 00:00 1 = 00
* @returns {String} 00:00:00
*/
function secondsToStr(seconds, level) {
var hours = parseInt(seconds / (60 * 60));
var minutes = parseInt(seconds / (60));
seconds = parseInt(seconds % (60));
hours = hours > 9 ? hours : "0" + hours;
minutes = minutes > 9 ? minutes : "0" + minutes;
seconds = seconds > 9 ? seconds : "0" + seconds;
switch (level) {
case 3:
return hours + ":" + minutes + ":" + seconds;
break;
case 2:
return minutes + ":" + seconds;
break;
case 1:
return seconds;
break;
default:
return hours + ":" + minutes + ":" + seconds;
}
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function subscribe(email, user_id) {
$.ajax({
url: webSiteRootURL + 'objects/subscribe.json.php',
method: 'POST',
data: {
'email': email,
'user_id': user_id
},
success: function (response) {
if (response.subscribe == "i") {
$('.subs' + user_id).removeClass("subscribed");
$('.subs' + user_id + ' b.text').text("Subscribe");
$('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) - 1);
} else {
$('.subs' + user_id).addClass("subscribed");
$('.subs' + user_id + ' b.text').text("Subscribed");
$('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) + 1);
}
$('#popover-content #subscribeEmail').val(email);
$('.subscribeButton' + user_id).popover('hide');
}
});
}
function subscribeNotify(email, user_id) {
$.ajax({
url: webSiteRootURL + 'objects/subscribeNotify.json.php',
method: 'POST',
data: {
'email': email,
'user_id': user_id
},
success: function (response) {
if (response.notify) {
$('.notNotify' + user_id).addClass("hidden");
$('.notify' + user_id).removeClass("hidden");
} else {
$('.notNotify' + user_id).removeClass("hidden");
$('.notify' + user_id).addClass("hidden");
}
}
});
}
function mouseEffect() {
$(".thumbsImage").on("mouseenter", function () {
var gif = $(this).find(".thumbsGIF");
var jpg = $(this).find(".thumbsJPG");
try {
gif.lazy({effect: 'fadeIn'});
setTimeout(function () {
gif.height(jpg.height());
gif.width(jpg.width());
}, 100);
} catch (e) {
}
gif.height(jpg.height());
gif.width(jpg.width());
gif.stop(true, true).fadeIn();
});
$(".thumbsImage").on("mouseleave", function () {
$(this).find(".thumbsGIF").stop(true, true).fadeOut();
});
}
function isMobile() {
var check = false;
(function (a) {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)))
check = true
})(navigator.userAgent || navigator.vendor || window.opera);
return check;
}
var last_videos_id = 0;
var last_currentTime = -1;
function addView(videos_id, currentTime) {
if (last_videos_id == videos_id && last_currentTime == currentTime) {
return false;
}
last_videos_id = videos_id;
last_currentTime = currentTime;
$.ajax({
url: webSiteRootURL + 'objects/videoAddViewCount.json.php',
method: 'POST',
data: {
'id': videos_id,
'currentTime': currentTime
},
success: function (response) {
$('.view-count' + videos_id).text(response.count);
}
});
}
function getPlayerButtonIndex(name) {
var children = player.getChild('controlBar').children();
for (i = 0; i < children.length; i++) {
if (children[i].name_ === name) {
return i;
}
}
return children.length;
}
function copyToClipboard(text) {
$('#elementToCopy').css({'top': mouseY, 'left': 0}).fadeIn('slow');
$('#elementToCopy').val(text);
$('#elementToCopy').focus();
$('#elementToCopy').select();
document.execCommand('copy');
$('#elementToCopy').hide();
$.toast("Copied to Clipboard");
}
function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? ' ' : ' ';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
function playerIsReady() {
return (typeof player !== 'undefined' && player.isReady_);
}
var promisePlaytry = 20;
var promisePlayTimeoutTime = 500;
var promisePlayTimeout;
var promisePlay;
var browserPreventShowed = false;
var playerPlayTimeout;
function playerPlay(currentTime) {
clearTimeout(playerPlayTimeout);
if (currentTime) {
console.log("playerPlay time:", currentTime);
}
if (!playerIsReady()) {
playerPlayTimeout = setTimeout(function () {
playerPlay(currentTime);
}, 200);
return false;
}
if (userIsControling) { // stops here if the user already clicked on play or pause
console.log("playerPlay: userIsControling");
return true;
}
if (promisePlaytry <= 0) {
console.log("playerPlay: promisePlaytry <= 0");
if (!browserPreventShowed) {
browserPreventShowed = true;
$.toast("Your browser prevent autoplay");
}
return false;
}
promisePlaytry--;
if (typeof player !== 'undefined') {
if (currentTime) {
player.currentTime(currentTime);
}
try {
console.log("playerPlay: Trying to play", player);
promisePlay = player.play();
if (promisePlay !== undefined) {
tryToPlay(currentTime);
console.log("playerPlay: promise found");
promisePlay.then(function () {
console.log("playerPlay: Autoplay started");
userIsControling = true;
if (player.paused()) {
console.log("The video still paused, trying to mute and play");
if (promisePlaytry <= 10) {
console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to mute and play");
tryToPlayMuted(currentTime);
} else {
console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to play again");
tryToPlay(currentTime);
}
} else {
//player.muted(false);
if (player.muted() && !inIframe()) {
showUnmutePopup();
}
}
}).catch(function (error) {
if (player.networkState() === 3) {
promisePlaytry = 20;
console.log("playerPlay: Network error detected, trying again");
player.src(player.currentSources());
userIsControling = false;
tryToPlay(currentTime);
} else {
if (promisePlaytry <= 10) {
console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to mute and play ***");
tryToPlayMuted(currentTime);
} else {
console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to play again");
tryToPlay(currentTime);
}
}
});
} else {
tryToPlay(currentTime);
}
} catch (e) {
console.log("playerPlay: We could not autoplay, trying again in 1 second");
tryToPlay(currentTime);
}
} else {
console.log("playerPlay: Player is Undefined");
}
}
function showUnmutePopup() {
var donotShowUnmuteAgain = Cookies.get('donotShowUnmuteAgain');
if (!donotShowUnmuteAgain) {
var span = document.createElement("span");
span.innerHTML = "Would you like to unmute it?
";
swal({
title: "Your Media is Muted",
icon: "warning",
content: span,
dangerMode: true,
buttons: {
cancel: "Cancel",
unmute: true,
donotShowUnmuteAgain: {
text: "Don't show again",
value: "donotShowUnmuteAgain",
className: "btn-danger",
},
}
}).then(function (value) {
switch (value) {
case "unmute":
player.muted(false);
break;
case "donotShowUnmuteAgain":
Cookies.set('donotShowUnmuteAgain', true, {
path: '/',
expires: 365
});
break;
}
});
}
showMuteTooltip();
setTimeout(function () {
$("#allowAutoplay").load(webSiteRootURL + "plugin/PlayerSkins/allowAutoplay/");
player.userActive(true);
}, 500);
}
function tryToPlay(currentTime) {
clearTimeout(promisePlayTimeout);
promisePlayTimeout = setTimeout(function () {
if (player.paused()) {
playerPlayTimeout = setTimeout(function () {
playerPlay(currentTime);
}, 200);
}
}, promisePlayTimeoutTime);
}
function tryToPlayMuted(currentTime) {
muteInCookieAllow();
return tryToPlay(currentTime);
}
function muteIfNotAudio() {
if (!player.isAudio()) {
console.log("muteIfNotAudio: We will mute this video");
player.muted(true);
return true;
}
console.log("muteIfNotAudio: We will not mute an audio");
return false;
}
function muteInCookieAllow() {
var mute = Cookies.get('muted');
if (isALiveContent() || typeof mute === 'undefined' || (mute && mute !== "false")) {
console.log("muteInCookieAllow: said yes");
return muteIfNotAudio();
}
console.log("muteInCookieAllow: said no");
return false;
}
function playMuted(currentTime) {
muteInCookieAllow();
playerPlayTimeout = setTimeout(function () {
playerPlay(currentTime);
}, 200);
}
function showMuteTooltip() {
if ($("#mainVideo .vjs-volume-panel").length) {
if (!$("#mainVideo .vjs-volume-panel").is(":visible")) {
setTimeout(function () {
showMuteTooltip();
}, 500);
return false;
}
$("#mainVideo .vjs-volume-panel").attr("data-toggle", "tooltip");
$("#mainVideo .vjs-volume-panel").attr("data-placement", "top");
$("#mainVideo .vjs-volume-panel").attr("title", "Click to activate the sound");
$('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip({container: '.vjs-control-bar'});
$('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('show');
$("#mainVideo .vjs-volume-panel").click(function () {
console.log("remove unmute tooltip");
$('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide');
$("#mainVideo .vjs-volume-panel").removeAttr("data-toggle");
$("#mainVideo .vjs-volume-panel").removeAttr("data-placement");
$("#mainVideo .vjs-volume-panel").removeAttr("title");
$("#mainVideo .vjs-volume-panel").removeData('tooltip').unbind().next('div.tooltip').remove();
});
}
player.userActive(true);
setTimeout(function () {
player.userActive(true);
}, 1000);
setTimeout(function () {
player.userActive(true);
}, 1500);
setTimeout(function () {
$('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide');
}, 5000);
}
function playerPlayIfAutoPlay(currentTime) {
if (isAutoplayEnabled()) {
playerPlayTimeout = setTimeout(function () {
playerPlay(currentTime);
}, 200);
return true;
}
setCurrentTime(currentTime);
//$.toast("Autoplay disabled");
return false;
}
function playNext(url) {
if (isPlayingAds()) {
setTimeout(function () {
playNext(url);
}, 1000);
} else if (isPlayNextEnabled()) {
modal.showPleaseWait();
if (typeof autoPlayAjax == 'undefined' || !autoPlayAjax) {
console.log("playNext changing location " + url);
document.location = url;
} else {
console.log("playNext ajax");
$.ajax({
url: webSiteRootURL + 'view/infoFromURL.php?url=' + encodeURI(url),
success: function (response) {
console.log(response);
if (!response || response.error) {
console.log("playNext ajax fail");
//document.location = url;
} else {
console.log("playNext ajax success");
$('topInfo').hide();
playNextURL = isEmbed ? response.nextURLEmbed : response.nextURL;
console.log("New playNextURL", playNextURL);
if (!changeVideoSrc(player, response.sources)) {
document.location = url;
return false;
}
$('video, #mainVideo').attr('poster', response.poster);
history.pushState(null, null, url);
$('.vjs-thumbnail-holder, .vjs-thumbnail-holder img').attr('src', response.sprits);
modal.hidePleaseWait();
if ($('#modeYoutubeBottom').length) {
$.ajax({
url: url,
success: function (response) {
modeYoutubeBottom = $(response).find('#modeYoutubeBottom').html();
$('#modeYoutubeBottom').html(modeYoutubeBottom);
}
});
}
}
}
});
}
} else if (isPlayerLoop()) {
$.toast("Looping video");
userIsControling = false;
playerPlayTimeout = setTimeout(function () {
playerPlay(currentTime);
}, 200);
}
}
function formatBytes(bytes, decimals) {
if (bytes == 0)
return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function tooglePlayerLoop() {
setPlayerLoop(!isPlayerLoop());
}
var setPlayerLoopSetTimeout;
function setPlayerLoop(loop) {
clearTimeout(setPlayerLoopSetTimeout);
if (typeof player === 'undefined') {
setPlayerLoopSetTimeout = setTimeout(function () {
setPlayerLoop(loop)
}, 1000);
return false;
}
if (loop) {
console.log("Loop ON");
//$.toast("Loop ON");
player.loop(1);
$(".loop-button").removeClass('loop-disabled-button');
$(".loop-button, .loopButton").addClass('fa-spin');
} else {
$(".loop-button").addClass('loop-disabled-button');
$(".loop-button, .loopButton").removeClass('fa-spin');
console.log("Loop OFF");
//$.toast("Loop OFF");
player.loop(0);
}
Cookies.set('playerLoop', loop, {
path: '/',
expires: 365
});
if (typeof setImageLoop === 'function') {
setImageLoop();
}
}
function setImageLoop() {
if (isPlayerLoop()) {
$('.loopButton').removeClass('opacityBtn');
$('.loopButton').addClass('fa-spin');
} else {
$('.loopButton').addClass('opacityBtn');
$('.loopButton').removeClass('fa-spin');
}
}
function toogleImageLoop(t) {
tooglePlayerLoop();
if (typeof setImageLoop === 'function') {
setImageLoop();
}
}
function isPlayerLoop() {
if (typeof player === 'undefined') {
return false;
}
var loop = Cookies.get('playerLoop');
if (!loop || loop === "false") {
return player.loop();
} else {
return true;
}
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function reloadVideoJS() {
if (typeof player.currentSources === 'function') {
var src = player.currentSources();
player.src(src);
}
}
var initdone = false;
function setCurrentTime(currentTime) {
if (typeof player !== 'undefined') {
player.currentTime(currentTime);
initdone = false;
// wait for video metadata to load, then set time
player.on("loadedmetadata", function () {
player.currentTime(currentTime);
});
// iPhone/iPad need to play first, then set the time
// events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents
player.on("canplaythrough", function () {
if (!initdone) {
player.currentTime(currentTime);
initdone = true;
}
});
} else {
setTimeout(function () {
setCurrentTime(currentTime);
}, 1000);
}
}
function isALiveContent() {
if (typeof isLive !== 'undefined' && isLive) {
return true;
}
return false;
}
function isAutoplayEnabled() {
console.log("Cookies.get('autoplay')", Cookies.get('autoplay'));
if (isALiveContent()) {
console.log("isAutoplayEnabled always autoplay live contents");
return true;
} else
if ($("#autoplay").length && $("#autoplay").is(':visible')) {
autoplay = $("#autoplay").is(":checked");
console.log("isAutoplayEnabled #autoplay said " + ((autoplay) ? "Yes" : "No"));
setAutoplay(autoplay);
return autoplay;
} else if (
typeof Cookies !== 'undefined' &&
typeof Cookies.get('autoplay') !== 'undefined'
) {
if (Cookies.get('autoplay') === 'true' || Cookies.get('autoplay') == true) {
console.log("isAutoplayEnabled Cookie said Yes ");
setAutoplay(true);
return true;
} else {
console.log("isAutoplayEnabled Cookie said No ");
setAutoplay(false);
return false;
}
} else {
if (typeof autoplay !== 'undefined') {
console.log("isAutoplayEnabled autoplay said " + ((autoplay) ? "Yes" : "No"));
setAutoplay(autoplay);
return autoplay;
}
}
setAutoplay(false);
console.log("isAutoplayEnabled Default is No ");
return false;
}
function setAutoplay(value) {
Cookies.set('autoplay', value, {
path: '/',
expires: 365
});
}
function isPlayNextEnabled() {
if (isPlayerLoop()) {
return false;
} else if (isAutoplayEnabled()) {
return true;
}
return false;
}
function avideoAlert(title, msg, type) {
if (msg !== msg.replace(/<\/?[^>]+(>|$)/g, "")) {//it has HTML
avideoAlertHTMLText(title, msg, type);
} else {
swal(title, msg, type);
}
}
function avideoToast(msg) {
$.toast(msg);
}
function avideoAlertAJAXHTML(url) {
modal.showPleaseWait();
$.ajax({
url: url,
success: function (response) {
avideoAlertText(response);
modal.hidePleaseWait();
}
});
}
function avideoAlertHTMLText(title, msg, type) {
var span = document.createElement("span");
span.innerHTML = msg;
swal({
title: title,
content: span,
icon: type,
closeModal: true,
buttons: type ? true : false,
});
}
function avideoAlertText(msg) {
avideoAlert("", msg, '');
}
function avideoAlertInfo(msg) {
avideoAlert("Info", msg, 'info');
}
function avideoAlertError(msg) {
avideoAlert("Error", msg, 'error');
}
function avideoAlertSuccess(msg) {
avideoAlert("Success", msg, 'success');
}
function avideoTooltip(selector, text) {
$(selector).attr('title', text);
$(selector).attr('data-toggle', 'tooltip');
$(selector).attr('data-original-title', text);
$(selector).tooltip();
}
function fixAdSize() {
ad_container = $('#mainVideo_ima-ad-container');
if (ad_container.length) {
height = ad_container.css('height');
width = ad_container.css('width');
$($('#mainVideo_ima-ad-container div:first-child')[0]).css({'height': height});
$($('#mainVideo_ima-ad-container div:first-child')[0]).css({'width': width});
}
}
function isPlayingAds() {
return ($("#mainVideo_ima-ad-container").length && $("#mainVideo_ima-ad-container").is(':visible'));
}
function playerHasAds() {
return ($("#mainVideo_ima-ad-container").length > 0);
}
function countTo(selector, total) {
var text = $(selector).text();
if (isNaN(text)) {
current = 0;
} else {
current = parseInt(text);
}
total = parseInt(total);
if (!total || current >= total) {
$(selector).removeClass('loading');
return;
}
var rest = (total - current);
var step = parseInt(rest / 100);
if (step < 1) {
step = 1;
}
current += step;
$(selector).text(current);
var timeout = (500 / rest);
setTimeout(function () {
countTo(selector, total);
}, timeout);
}
$(document).ready(function () {
modal = modal || (function () {
var pleaseWaitDiv = $("#pleaseWaitDialog");
if (pleaseWaitDiv.length === 0) {
pleaseWaitDiv = $('').appendTo('body');
}
return {
showPleaseWait: function () {
if (pleaseWaitIsINUse) {
return false;
}
pleaseWaitIsINUse = true;
pleaseWaitDiv.modal();
},
hidePleaseWait: function () {
pleaseWaitDiv.modal('hide');
pleaseWaitIsINUse = false;
},
setProgress: function (valeur) {
pleaseWaitDiv.find('.progress-bar').css('width', valeur + '%').attr('aria-valuenow', valeur);
},
setText: function (text) {
pleaseWaitDiv.find('h2').html(text);
},
};
})();
try {
$('[data-toggle="popover"]').popover();
} catch (e) {
}
-
- setInterval(function(){setToolTips();},1000);
+
+ setInterval(function () {
+ setToolTips();
+ }, 1000);
$(".thumbsImage").on("mouseenter", function () {
gifId = $(this).find(".thumbsGIF").attr('id');
$(".thumbsGIF").fadeOut();
if (gifId != undefined) {
id = gifId.replace('thumbsGIF', '');
var gif = $(this).find(".thumbsGIF");
var jpg = $(this).find(".thumbsGIF");
gif.height(jpg.height());
gif.width(jpg.width());
try {
gif.lazy({effect: 'fadeIn'});
} catch (e) {
}
gif.stop(true, true).fadeIn();
}
});
$(".thumbsImage").on("mouseleave", function () {
$(this).find(".thumbsGIF").stop(true, true).fadeOut();
});
lazyImage();
$("a").each(function () {
var location = window.location.toString()
var res = location.split("?");
pathWitoutGet = res[0];
if ($(this).attr("href") == window.location.pathname
|| $(this).attr("href") == window.location
|| $(this).attr("href") == pathWitoutGet) {
$(this).addClass("selected");
}
});
$('#clearCache, .clearCacheButton').on('click', function (ev) {
ev.preventDefault();
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'objects/configurationClearCache.json.php',
success: function (response) {
if (!response.error) {
avideoAlert("Congratulations!", "Your cache has been cleared!", "success");
} else {
avideoAlert("Sorry!", "Your cache has NOT been cleared!", "error");
}
modal.hidePleaseWait();
}
});
});
$('.clearCacheFirstPageButton').on('click', function (ev) {
ev.preventDefault();
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'objects/configurationClearCache.json.php?FirstPage=1',
success: function (response) {
if (!response.error) {
avideoAlert("Congratulations!", "Your First Page cache has been cleared!", "success");
} else {
avideoAlert("Sorry!", "Your First Page cache has NOT been cleared!", "error");
}
modal.hidePleaseWait();
}
});
});
$('#generateSiteMap, .generateSiteMapButton').on('click', function (ev) {
ev.preventDefault();
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'objects/configurationGenerateSiteMap.json.php',
success: function (response) {
if (!response.error) {
avideoAlert("Congratulations!", "File created!", "success");
} else {
if (response.msg) {
avideoAlert("Sorry!", response.msg, "error");
} else {
avideoAlert("Sorry!", "File NOT created!", "error");
}
}
modal.hidePleaseWait();
}
});
});
setPlayerListners();
$('.duration:contains("00:00:00"), .duration:contains("EE:EE:EE")').hide();
});
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+:]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
return !!pattern.test(str);
}
-function isURL(url){
+function isURL(url) {
return validURL(url);
}
function startTimer(duration, selector) {
var timer = duration;
var startTimerInterval = setInterval(function () {
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(duration / (60 * 60 * 24));
var hours = Math.floor((duration % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor((duration % (60 * 60)) / (60));
var seconds = Math.floor((duration % (60)));
// Display the result in the element with id="demo"
var text = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
$(selector).text(text);
duration--;
// If the count down is finished, write some text
if (duration < 0) {
clearInterval(startTimerInterval);
$(selector).text("EXPIRED");
}
}, 1000);
}
function addGetParam(_url, _key, _value) {
var param = _key + '=' + escape(_value);
var sep = '&';
if (_url.indexOf('?') < 0) {
sep = '?';
} else {
var lastChar = _url.slice(-1);
if (lastChar == '&')
sep = '';
if (lastChar == '?')
sep = '';
}
_url += sep + param;
return _url;
}
function readFileCroppie(input, crop) {
if ($(input)[0].files && $(input)[0].files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
crop.croppie('bind', {
url: e.target.result
}).then(function () {
console.log('jQuery bind complete');
});
}
reader.readAsDataURL($(input)[0].files[0]);
} else {
avideoAlert("Sorry - you're browser doesn't support the FileReader API");
}
}
function getCroppie(uploadCropObject, callback, width, height) {
uploadCropObject.croppie('result', {type: 'base64', size: {width: width, height: height}, format: 'png'}).then(function (resp) {
eval(callback + "(resp);");
});
}
function setToolTips() {
- if(!$('[data-toggle="tooltip"]').not('.alreadyTooltip').length){
+ if (!$('[data-toggle="tooltip"]').not('.alreadyTooltip').length) {
return false;
}
$('[data-toggle="tooltip"]').not('.alreadyTooltip').tooltip({container: 'body'});
$('[data-toggle="tooltip"]').not('.alreadyTooltip').on('click', function () {
var t = this;
setTimeout(function () {
$(t).tooltip('hide');
}, 2000);
});
$('[data-toggle="tooltip"]').addClass('alreadyTooltip');
+}
+
+function avideoSocketIsActive() {
+ if (typeof isSocketActive == 'function') {
+ return isSocketActive();
+ } else {
+ return false;
+ }
}
\ No newline at end of file
diff --git a/view/managerUsers_body.php b/view/managerUsers_body.php
index 2e629465e..60a9a13b9 100644
--- a/view/managerUsers_body.php
+++ b/view/managerUsers_body.php
@@ -1,465 +1,468 @@
diff --git a/view/managerVideos_body.php b/view/managerVideos_body.php
index 7a452fdd2..b9a428917 100644
--- a/view/managerVideos_body.php
+++ b/view/managerVideos_body.php
@@ -1,2164 +1,2166 @@
$secondsTotal) {
$percent = intval($secondsTotal / $secondsLimit * 100);
} else {
$percent = 100;
}
?> and you have minutes of storage
% of your storage limit used
disableDownloadVideosList)) {
?>
getDisable_youtubeupload())) {
?>
:
" . __("Google ID and Key") . ""; ?>
" . __("YouTube Data API") . " v3"; ?>
:
objects/youtubeUpload.json.php
:
diff --git a/view/userGetPhoto.php b/view/userGetPhoto.php
new file mode 100644
index 000000000..075c2ec2d
--- /dev/null
+++ b/view/userGetPhoto.php
@@ -0,0 +1,8 @@
+thumbnails;
$poster = $evideo->thumbnails;
$imgw = 1280;
$imgh = 720;
$autoPlaySources = array();
$autoPlayURL = '';
$autoPlayPoster = '';
$autoPlayThumbsSprit = '';
} else if (!empty($_GET['v'])) {
$video = Video::getVideo($_GET['v'], "", true, false, false, true);
//$video['id'] = $_GET['v'];
} else if (!empty($_GET['videoName'])) {
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
Video::unsetAddView($video['id']);
AVideoPlugin::getEmbed($video['id']);
if (empty($video)) {
forbiddenPage("Video not found");
}
if(empty($video['users_id'])){
$video['users_id'] = User::getId();
}
if (empty($customizedAdvanced)) {
$customizedAdvanced = AVideoPlugin::getObjectDataIfEnabled('CustomizeAdvanced');
}
if (!isSameDomain(@$_SERVER['HTTP_REFERER'], $global['webSiteRootURL']) && !isAVideoMobileApp()) {
if (!empty($advancedCustomUser->blockEmbedFromSharedVideos) && !CustomizeUser::canShareVideosFromVideo($video['id'])) {
if (!empty($advancedCustomUser->blockEmbedFromSharedVideos)) {
error_log("Embed is forbidden: \$advancedCustomUser->blockEmbedFromSharedVideos");
}
if (!CustomizeUser::canShareVideosFromVideo($video['id'])) {
error_log("Embed is forbidden: !CustomizeUser::canShareVideosFromVideo(\$video['id'])");
}
forbiddenPage("Embed is forbidden");
}
}
$imgw = 1280;
$imgh = 720;
if ($video['type'] !== "pdf") {
if(!empty($video['filename'])){
$source = Video::getSourceFile($video['filename']);
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
}else{
$source = array();
$img = "";
$imgw = 0;
$imgh = 0;
}
} else if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio")) {
$source = Video::getSourceFile($video['filename']);
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
if(!empty($video['filename'])){
$images = Video::getImageFromFilename($video['filename']);
$poster = $images->poster;
if (!empty($images->posterPortrait)) {
$img = $images->posterPortrait;
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
}
}else{
$images = array();
$poster = "";
$imgw = 0;
$imgh = 0;
}
require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
/*
* Swap aspect ratio for rotated (vvs) videos
if ($video['rotation'] === "90" || $video['rotation'] === "270") {
$embedResponsiveClass = "embed-responsive-9by16";
$vjsClass = "vjs-9-16";
} else {
$embedResponsiveClass = "embed-responsive-16by9";
$vjsClass = "vjs-16-9";
} */
$vjsClass = "";
$obj = new Video("", "", $video['id']);
$resp = $obj->addView();
if(!empty($video['filename'])){
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio")) {
$poster = "{$global['webSiteRootURL']}videos/{$video['filename']}.jpg";
} else {
$poster = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
}
//https://.../vEmbed/527?modestbranding=1&showinfo=0&autoplay=1&controls=0&loop=1&mute=1&t=0
$modestbranding = false;
$autoplay = false;
$controls = "controls";
$loop = "";
$mute = "";
$objectFit = "";
$t = 0;
if (isset($_GET['modestbranding']) && $_GET['modestbranding'] == "1") {
$modestbranding = true;
}
if (!empty($_GET['autoplay']) || $config->getAutoplay()) {
$autoplay = true;
}
if (isset($_GET['controls']) && $_GET['controls'] == "0") {
$controls = "";
}
if (!empty($_GET['loop'])) {
$loop = "loop";
}
if (!empty($_GET['mute'])) {
$mute = 'muted="muted"';
}
if (!empty($_GET['objectFit'])) {
$objectFit = 'object-fit: ' . $_GET['objectFit'];
}
if (!empty($_GET['t'])) {
$t = intval($_GET['t']);
} else if (!empty($video['progress']['lastVideoTime'])) {
$t = intval($video['progress']['lastVideoTime']);
} else if (!empty($video['externalOptions']->videoStartSeconds)) {
$t = parseDurationToSeconds($video['externalOptions']->videoStartSeconds);
}
$playerSkinsO = AVideoPlugin::getObjectData("PlayerSkins");
$disableEmbedTopInfo = $playerSkinsO->disableEmbedTopInfo;
+if(isset($_REQUEST['showinfo']) && empty($_REQUEST['showinfo'])){
+ $disableEmbedTopInfo = true;
+ $modestbranding = true;
+}
+
$url = Video::getLink($video['id'], $video['clean_title'], false);
$title = str_replace('"', '', $video['title']) . ' - ' . $config->getWebSiteTitle();
$photo = User::getPhoto($video['users_id']);
if (empty($currentTime)) {
$currentTime = 0;
}
if (User::hasBlockedUser($video['users_id'])) {
$disableEmbedTopInfo = true;
$video['type'] = "blockedUser";
}
?>
getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
You've blocked user ()
You won't see any comments or videos from this user
" class="img img-responsive" style="height: 100%;" >
open($sources['zip']["path"]);
for ($i = 0; $i < $za->numFiles; $i++) {
$stat = $za->statIndex($i);
$fname = basename($stat['name']);
?>
class="center-block video-js vjs-default-skin vjs-big-play-centered" id="mainVideo" data-setup='{ "fluid": true }'
poster="view/img/recorder.gif">
horse
horse
class="video-js vjs-default-skin vjs-big-play-centered " id="mainVideo">
" >
";
echo getVTTTracks($video['filename']);
}
?>
class="video-js vjs-default-skin vjs-big-play-centered " id="mainVideo">
' . $subscribe . '